一、MethodInfo类
MethodInfo是System.Reflection命名空间下的一个类,它表示一个方法,可以获取到该方法的名称、返回值类型、参数类型、访问修饰符、是否静态等等信息。
在代码中,可以通过Type类的GetMethod方法获取MethodInfo对象,例如下面的代码:
class MyClass{ public void MyMethod(int arg){ Console.WriteLine("MyMethod被调用了,参数为:"+arg); } } //获取MyClass类中名为MyMethod,参数为int的方法的MethodInfo对象 Type typeOfMyClass = typeof(MyClass); MethodInfo myMethodInfo = typeOfMyClass.GetMethod("MyMethod", new Type[]{typeof(int)});
在上述代码中,typeof是C#中的关键字,可以获取到某个类型的Type对象。GetMethod方法的第一个参数是方法名称,第二个参数是一个Type数组,表示方法的参数类型。
二、MethodInfo.Invoke
MethodInfo.Invoke方法可以调用一个方法,返回值是object类型,可以根据方法的返回值类型进行类型转换。如果方法没有返回值,则返回null。例如下面的代码:
object result = myMethodInfo.Invoke(new MyClass(), new object[]{123}); Console.WriteLine("方法的返回值为:"+(int)result);
在上述代码中,第一个参数是方法所属的对象实例,如果该方法是静态的,该参数可以传入null。第二个参数是一个object数组,表示方法的参数值。在这个例子中,传入了一个MyClass的实例对象和一个int类型的参数值123,这个MyMethod方法会被调用,并输出结果“MyMethod被调用了,参数为:123”。而返回值就是MyMethod这个方法的返回值,即123。
三、MethodInfo to Func
MethodInfo可以通过转换为Func委托类型,从而使得动态调用性能更好。例如下面的代码:
Func<MyClass, int, int> myMethodDelegate = (Func<MyClass, int, int>)Delegate.CreateDelegate(typeof(Func<MyClass, int, int>), myMethodInfo); int result2 = myMethodDelegate(new MyClass(), 321); Console.WriteLine("方法的返回值为:"+result2);
在上述代码中,Delegate.CreateDelegate方法可以将MethodInfo对象转换为Func委托类型。这里将MethodInfo对象myMethodInfo转换为Func<MyClass, int, int>类型,表示该委托类型接受两个参数,一个MyClass类型的参数类型,一个int类型的参数类型,返回值是int类型。这里也传入了一个MyClass的实例对象和一个int类型的参数值,这个MyMethod方法也会被调用,并输出结果“MyMethod被调用了,参数为:321”。而返回值就是MyMethod这个方法的返回值,即321。
四、MethodInfo获取属性的getter或setter方法
对于属性,需要使用反射获取其getter或setter方法,可以通过MethodInfo对象完成。假设有以下代码:
class MyClass{ public int MyProperty{get;set;} }
可以使用GetMethod方法获取到getter或setter方法的MethodInfo对象:
Type typeOfMyClass = typeof(MyClass); MethodInfo getPropertyMethod = typeOfMyClass.GetProperty("MyProperty").GetGetMethod(); MethodInfo setPropertyMethod = typeOfMyClass.GetProperty("MyProperty").GetSetMethod();
在上述代码中,GetProperty方法获取到属性的PropertyInfo对象,而GetGetMethod和GetSetMethod方法可以获取到其getter和setter方法的MethodInfo对象。
原创文章,作者:LCYFV,如若转载,请注明出处:https://www.506064.com/n/334547.html