C#中如何访问继承类中修饰符为protected的函数?
不修改访问修饰符调用protected方法的几种方案
针对这个问题,这里提供三种可行方案,无需将mult方法改为public:
方案1:在子类中添加public代理方法(推荐)
这是最符合C#封装原则的做法,利用子类可访问父类protected成员的特性,新增一个public方法作为代理:
public class a { protected virtual int mult(int x) { return x * x; } } public class b : a { protected override int mult(int x) { return x * x * x; } // 新增public代理方法,内部调用protected的mult public int InvokeMult(int x) { return mult(x); } } internal class Program { static void Main(string[] args) { b jack = new b(); int v = jack.InvokeMult(5); // 正常调用,返回125 } }
方案2:使用反射(不推荐,仅特殊场景使用)
通过反射可以绕过访问权限检查,但会带来性能开销,且破坏封装性,仅建议在调试或非常规场景下使用:
using System.Reflection; public class a { protected virtual int mult(int x) { return x * x; } } public class b : a { protected override int mult(int x) { return x * x * x; } } internal class Program { static void Main(string[] args) { b jack = new b(); // 获取非公开实例方法mult MethodInfo multMethod = typeof(b).GetMethod("mult", BindingFlags.Instance | BindingFlags.NonPublic); // 调用方法并转换返回值 int v = (int)multMethod.Invoke(jack, new object[] { 5 }); } }
方案3:通过嵌套派生类访问
在Program类中定义一个从b派生的嵌套类,利用派生类对protected成员的访问权限,暴露调用入口:
public class a { protected virtual int mult(int x) { return x * x; } } public class b : a { protected override int mult(int x) { return x * x * x; } } internal class Program { // 嵌套派生类,可访问b的protected方法 private class BWrapper : b { public int CallMult(int x) { return mult(x); } } static void Main(string[] args) { BWrapper jack = new BWrapper(); int v = jack.CallMult(5); } }
内容的提问来源于stack exchange,提问作者Hussain
相关产品推荐
相关产品推荐

