从一个类中访问另一个类中的私有方法

一般情况下我们无法在一个类中去访问另外一个类中非公有的方法,但有时候我们确实需要调用另外一个类中的私有方法,该怎么办呢?

有两种方法可以解决,一个是利用反射,另一个就是用委托。

我们可以看个Demo:

 1 namespace ReflectTest
2 {
3 public class TypeAndMethod
4 {
5 public delegate int MyHandler(int x, int y);
6
7 //利用反射
8 public void CallAddByReflect()
9 {
10 TestMethod target = new TestInvokeMethod();
11 Type type = target.GetType();
12 MethodInfo method = type.GetMethod("Add", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
13
14 if (method == null) return;
15
16 object[] args = new object[] { 10, 20 };//方法的参数
17 object result = method.Invoke(target, args);
18
19 Console.WriteLine(result.ToString());
20 }
21
22 //利用委托
23 public void CallAddByDelegate()
24 {
25 TestMethod target = new TestInvokeMethod();
26 Type t1 = typeof(MyHandler);
27 Type t2 = typeof(TestInvokeMethod);
28
29 MyHandler handler1 = (MyHandler)Delegate.CreateDelegate(t1, t2, "Sub");//调用静态方法
30 MyHandler handler2 = (MyHandler)Delegate.CreateDelegate(t1, target, "Add");//调用实例方法
31 int result1 = handler1(1, 2);
32 int result2 = handler2(1, 2);
33 Console.WriteLine(result1.ToString());
34 Console.WriteLine(result2.ToString());
35 }
36 }
37
38 public class TestInvokeMethod : TestMethod
39 {
40 protected override int Add(int x, int y)
41 {
42 return x + y;
43 }
44
45 private static int Sub(int x, int y)
46 {
47 return x - y;
48 }
49 }
50
51 public abstract class TestMethod
52 {
53 protected abstract int Add(int x, int y);
54 }
55 }


 

转载于:https://www.cnblogs.com/chenlinfei/archive/2011/12/11/2283951.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值