1. 程式人生 > >C# 反射,通過類名、方法名調用方法

C# 反射,通過類名、方法名調用方法

inf tle dba nbsp tel str ati param ren

  在 C# 代碼中,有些時候只知道方法的名字(string),需要調用該方法,那麽就需要用到 C# 的反射機制。下面是一個簡單的 demo。

技術分享圖片
 1 using System;
 2 using System.Reflection;
 3 
 4 class Test
 5 {
 6     // 無參數,無返回值方法
 7     public void Method()
 8     {
 9         Console.WriteLine("Method(無參數) 調用成功!");
10     }
11 
12     // 有參數,無返回值方法
13     public void Method(string str)
14     {
15         Console.WriteLine("Method(有參數) 調用成功!參數 :" + str);
16     }
17 
18     // 有參數,有返回值方法
19     public string Method(string str1, string str2)
20     {
21         Console.WriteLine("Method(有參數,有返回值) 調用成功!參數 :" + str1 + ", " + str2);
22         string className = this.GetType().FullName;         // 非靜態方法獲取類名
23         return className;
24     }
25 }
26 
27 class Program
28 {
29     static void Main(string[] args)
30     {
31         string strClass = "Test";           // 命名空間+類名
32         string strMethod = "Method";        // 方法名
33 
34         Type type;                          // 存儲類
35         Object obj;                         // 存儲類的實例
36 
37         type = Type.GetType(strClass);      // 通過類名獲取同名類
38         obj = System.Activator.CreateInstance(type);       // 創建實例
39 
40         MethodInfo method = type.GetMethod(strMethod, new Type[] {});      // 獲取方法信息
41         object[] parameters = null;
42         method.Invoke(obj, parameters);                           // 調用方法,參數為空
43 
44         // 註意獲取重載方法,需要指定參數類型
45         method = type.GetMethod(strMethod, new Type[] { typeof(string) });      // 獲取方法信息
46         parameters = new object[] {"hello"};
47         method.Invoke(obj, parameters);                             // 調用方法,有參數
48 
49         method = type.GetMethod(strMethod, new Type[] { typeof(string), typeof(string) });      // 獲取方法信息
50         parameters = new object[] { "hello", "你好" };
51         string result = (string)method.Invoke(obj, parameters);     // 調用方法,有參數,有返回值
52         Console.WriteLine("Method 返回值:" + result);                // 輸出返回值
53 
54         // 獲取靜態方法類名
55         string className = MethodBase.GetCurrentMethod().ReflectedType.FullName;
56         Console.WriteLine("當前靜態方法類名:" + className);
57 
58         Console.ReadKey();
59     }
60 }
技術分享圖片

  需要註意的是,類名是命名空間+類名,不然會找不到類。

C# 反射,通過類名、方法名調用方法