日期:2014-05-20  浏览次数:20721 次

遍历成员
我要写一个方法

传过来一个对象的实例,可以使任何类

我要遍历这个实例拥有多少成员和属性,并且要知道他们的名字,

请问怎么写这个方法?

------解决方案--------------------
用反射,代碼如下:
下面的程序是一个名为ReflectionExample的简单项目,里面包括MainClass.cs和InstanceClass.cs两个文件,MainClass里面利用字符串来创建InstanceClass类并且调用InstanceClass中的属性和方法,其中包括调用缺省构造函数和调用重载构造函数、调用无参数的成员函数和带参数的成员函数四个方法,还有一个ReturnString属性,程序如下。
InstanceClass.cs文件
using System;

namespace ReflectionExample
{
/// <summary>
/// InstanceClass 的摘要描述。
/// </summary>
public class InstanceClass
{
private string returnString;
public string ReturnString
{
get { return returnString ; }
set { returnString = value ;}
}

public InstanceClass()
{
//
// TODO: 在此加入建构函式的程序代码
//
this.returnString = "Creat object without Parameter ";
}

public InstanceClass( string str )
{
this.returnString = str;
}

public void FunctionWithoutParameter()
{
Console.WriteLine( "Function Without Parameter " );
}

public void FunctionWithParameter( string str )
{
Console.WriteLine( str );
}
}
}
MainClass.cs文件
using System;
using System.Reflection;

namespace ReflectionExample
{
/// <summary>
/// Class1 的摘要描述。
/// </summary>
class MainClass
{
private Type type = null;
/// <summary>
/// 应用程序的主进入点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此加入启动应用程序的程序代码
//
Type type = typeof(InstanceClass);//利用typeof来获得InstanceClass类型。
MainClass mainClass = new MainClass(type);//初始化MainClass类
mainClass.GetObjectMethod();//调用无参数的函数
mainClass.GetObjectMethod( "Function With Parameter " );//调用带参数的函数
mainClass.GetObjectProperty();//调用缺省构造函数来初始化InstanceClass中的ReturnString属性
mainClass.GetObjectProperty( "Creat object with Parameter ");//调用重载构造函数来初始化InstanceClass中的ReturnString属性
}

public MainClass( Type type )
{
this.type = type ;
}

public void GetObjectMethod()
{
try
{
//Activator.CreateInstance()调用类的缺省构造函数来创建实例
object o = Activator.CreateInstance( type );
//利用MethodInfo类来获得从指定类中的成员函数
MethodInfo mi = type.GetMethod( "FunctionWithoutParameter " );
//调用此成员函数
mi.Invoke( o , null );
}
catch( Exception ex )
{
Console.WriteLine( ex.Message );
}
finally
{
Console.ReadLine();
}
}

public void GetObjectMethod( string str )
{
try
{
object o = Activator.CreateInstance( type );
//利用MethodInfo类来获得从指定类中符合条件的成员函数
MethodInfo mi = type.GetMethod( "FunctionWithParameter " , BindingFlags.Public |BindingFlags.Instance , null , new Type[]{ typeof(string) } , null );
mi.Invoke( o , new object[]{ str } );
}
catch( Exception ex )
{
Console.WriteLine( ex.Message );
}
finally
{
Console.ReadLine();
}
}

public void GetObjectProperty( )
{
try
{
object o = Activator.CreateInstance( type );
//利用PropertyInfo类来获得从指定类中的属性
PropertyInfo pi = type.GetProperty( "ReturnString " , typeof(string) );
//打印属性值
Console.WriteLine( pi.GetValue( o , null ) );