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

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

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

我们可以看个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 }
复制代码


 

posted @   静女  阅读(2552)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示