反射之动态获取类型成员并执行调用
反射支持查找类型的信息,枚举类型的成员,执行对象的成员等与类型有关的操作。可以动态获取类型成员并执行调用。
首先通过
Class classInstace = new Class();
Type t = classInstace.GetType();
获得Type类的一个实例,Type类的方法多用于获取数据类型的成员信息,如:
MethodInfo[] methods = t.GetMethods();//获得数据类型(这里是Class类)的所有公共方法成员
PropertyInfo[] properties = t.GetPropertys();//获得数据类型的所有公共属性成员
MethodInfo method = t.GetMethod("MethodName");//获得数据类型的指定名称的公共方法成员,注意是GetMethod而不是GetMethods
PropertyInfo property = t.GetProperty("PropertyName");//获得数据类型的指定名称的属性成员
获得数据类型的成员信息后,可以调用该成员,如:
property.GetValue(classInstace, null);//获得属性的值,第一个参数是数据类型的实例(将获得其属性的对象),第二个参数用于索引化属性,这里没有使用第二个参数
通过这种方法,可以动态的查找未知类型的成员并执行调用。比如从一个基类继承了多个类,它们具有同一个方法签名,但实现不同的功能,如果在运行时不能事先确定当前使用的是哪个类的实例时就可以通过上面的这种方法实现正确调用相应的方法。用代码解释更清晰:
//Class1和Class2都有DoSomething方法,分别实现不同功能
public class Class1 : BaseClass
{
//...Class1的实现
public int DoSomething(int para)
{
}
}
public class Class2 : BaseClass
{
//...Class2的实现
public int DoSomething(int para)
{
}
}
public class WorkClass
{
[STAThread]
static void Main()
{
object c;
if(true)
c = new Class1();
else
c = new Class2();
//在调用Test时并不知道c是哪个类型的实例,只知道c所代表的类型实现了DoSomething方法
Test(c);
}
//获取未知类型的方法成员并执行调用
public void Test(object c)
{
Type t = typeof(c);
MethodInfo method = t.GetMethod("DoSomething");
method.Invoke(c, new object[] {1});//第二个参数是要传递给要调用的方法的参数
//上面这一句相当于 c1.DoSomething(1)或c2.DoSomething(1),而不用事先知道是哪个类的实例
}
}
首先通过
Class classInstace = new Class();
Type t = classInstace.GetType();
获得Type类的一个实例,Type类的方法多用于获取数据类型的成员信息,如:
MethodInfo[] methods = t.GetMethods();//获得数据类型(这里是Class类)的所有公共方法成员
PropertyInfo[] properties = t.GetPropertys();//获得数据类型的所有公共属性成员
MethodInfo method = t.GetMethod("MethodName");//获得数据类型的指定名称的公共方法成员,注意是GetMethod而不是GetMethods
PropertyInfo property = t.GetProperty("PropertyName");//获得数据类型的指定名称的属性成员
获得数据类型的成员信息后,可以调用该成员,如:
property.GetValue(classInstace, null);//获得属性的值,第一个参数是数据类型的实例(将获得其属性的对象),第二个参数用于索引化属性,这里没有使用第二个参数
通过这种方法,可以动态的查找未知类型的成员并执行调用。比如从一个基类继承了多个类,它们具有同一个方法签名,但实现不同的功能,如果在运行时不能事先确定当前使用的是哪个类的实例时就可以通过上面的这种方法实现正确调用相应的方法。用代码解释更清晰:
//Class1和Class2都有DoSomething方法,分别实现不同功能
public class Class1 : BaseClass
{
//...Class1的实现
public int DoSomething(int para)
{
}
}
public class Class2 : BaseClass
{
//...Class2的实现
public int DoSomething(int para)
{
}
}
public class WorkClass
{
[STAThread]
static void Main()
{
object c;
if(true)
c = new Class1();
else
c = new Class2();
//在调用Test时并不知道c是哪个类型的实例,只知道c所代表的类型实现了DoSomething方法
Test(c);
}
//获取未知类型的方法成员并执行调用
public void Test(object c)
{
Type t = typeof(c);
MethodInfo method = t.GetMethod("DoSomething");
method.Invoke(c, new object[] {1});//第二个参数是要传递给要调用的方法的参数
//上面这一句相当于 c1.DoSomething(1)或c2.DoSomething(1),而不用事先知道是哪个类的实例
}
}
浙公网安备 33010602011771号