利用反射调用private成员

                                                                              反射的一个重要应用  

•调用private方法,
•             Person p1 = new Person();
•            Type type = p1.GetType();
•            //BindingFlags.Instance表示是实例方法,也就是不是static方法
•            //MethodInfo mHaha =  type.GetMethod("Haha",BindingFlags.NonPublic|BindingFlags.Instance);
•            //mHaha.Invoke(p1, null);
View Code
 1 namespace 封闭的类库
 2 {
 3     public class Person
 4     {
 5         public void Haha()
 6         {
 7             Console.WriteLine("Haha");
 8         }
 9 
10         private void HeiHei()
11         {
12             Console.WriteLine("HeiHei");
13         }
14 
15         public static void Hello()
16         {
17         }
18     }
19 }


下面来调用上面类的private方法:

View Code
 1 using 封闭的类库;
 2 
 3 namespace 调用封闭的类库
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             //假设Person是微软写的类,如果调用私有成员HeiHei就可以完成任务
10 
11             Person p1 = new Person();
12             p1.Haha();
13 
14             Type typePerson = p1.GetType();
15             //反射可以调用私有的方法。逼不得已可以这么干!因为也许下个版本就没有这个方法
16             //MethodInfo methodHeiHei = typePerson.GetMethod("HeiHei");
17             //Non:非。
18             //Instance:实例
19             MethodInfo methodHeiHei = typePerson.GetMethod("HeiHei",
20                 BindingFlags.NonPublic | BindingFlags.Instance);
21             methodHeiHei.Invoke(p1, null);
22             //p1.HeiHei();
23             //methodHeiHei.GetMethodBody().GetILAsByteArray();
24 
25             Console.ReadKey();
26         }
27     }
28 }

 

 
posted @ 2013-03-18 14:52  Big.Eagle  阅读(207)  评论(0)    收藏  举报