一、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/zh-hk/n/334547.html