C# 反射,通过类名、方法名调用方法

  在 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 }

 

 

  需要注意的是,类名是命名空间+类名,不然会找不到类。

 

posted @ 2018-05-07 11:48  Just_for_Myself  阅读(19904)  评论(2编辑  收藏  举报