Reflect中MethodInfo使用方法

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Reflection;
 6 
 7 namespace MethodInfoInvokeDemo
 8 {
 9     public class ReflectTest
10     {
11         public void MethodWithNoParaNoReturn()
12         {
13             Console.WriteLine("不带参数且不返回值的方法");
14         }
15 
16         public string MethodWithNoPara()
17         {
18             Console.WriteLine("不带参数且有返回值的方法");
19             return "MethodWithNoPara";
20         }
21 
22         public string Method1(string str)
23         {
24             Console.WriteLine("带参数且有返回值的方法");
25             return str;
26         }
27 
28         public string Method2(string str, int index)
29         {
30             Console.WriteLine("带参数且有返回值的方法");
31             return str + index.ToString();
32         }
33 
34         public string Method3(string str, out string outStr)
35         {
36             outStr = "bbbb";
37             Console.WriteLine("带参数且有返回值的方法");
38             return str;
39         }
40 
41         public static string StaticMethod()
42         {
43             Console.WriteLine("静态方法");
44             return "cccc";
45         }
46     }
47 
48     class Program
49     {
50         static void Main(string[] args)
51         {
52             Type type = typeof(ReflectTest);
53             object reflectTest = Activator.CreateInstance(type);
54 
55             //不带参数且不返回值的方法的调用
56             MethodInfo methodInfo = type.GetMethod("MethodWithNoParaNoReturn");
57             methodInfo.Invoke(reflectTest, null);
58 
59             Console.WriteLine();
60 
61             //不带参数且有返回值的方法的调用
62             methodInfo = type.GetMethod("MethodWithNoPara");
63             Console.WriteLine(methodInfo.Invoke(reflectTest, null).ToString());
64 
65             Console.WriteLine();
66 
67             //带参数且有返回值的方法的调用
68             methodInfo = type.GetMethod("Method1", new Type[]{typeof(string)});
69             Console.WriteLine(methodInfo.Invoke(reflectTest, new object[]{"测试"}).ToString());
70 
71             Console.WriteLine();
72 
73             //带多个参数且有返回值的方法的调用
74             methodInfo = type.GetMethod("Method2", new Type[] { typeof(string), typeof(int) });
75             Console.WriteLine(methodInfo.Invoke(reflectTest, new object[] { "测试", 100 }).ToString());
76 
77             //Console.WriteLine();
78 
79             //methodInfo = type.GetMethod("Method3", new Type[] { typeof(string), typeof(string) });
80             //string outStr = "";
81             //Console.WriteLine(methodInfo.Invoke(reflectTest, new object[] { "测试", outStr }).ToString());
82 
83             Console.WriteLine();
84 
85             //静态方法的调用
86             methodInfo = type.GetMethod("StaticMethod");  
87             Console.WriteLine(methodInfo.Invoke(null, null).ToString());
88 
89             Console.ReadKey();
90         }
91     }
92 }

 

posted @ 2014-08-22 17:58  xfyn  阅读(550)  评论(0编辑  收藏  举报