.NET 5平台下C#接口受保护方法工作原理及调用问题咨询
C# 接口protected成员调用方案
基于.NET 5支持的C# 8+接口默认实现特性,接口中protected成员的默认访问范围为:仅派生接口、实现该接口的类型内部可访问,对应两个问题的解决方案如下:
问题1:如何在接口外部调用Method_InterfaceRealization方法
该方法是带默认实现的接口protected方法,要在外部调用必须通过中间层暴露访问入口,常用两种方案:
- 方案1:在实现类内部新增公开方法调用该接口方法
代码示例:
调用方式:public class SomeClass: ISomeInterface { void ISomeInterface.Method1() { Console.WriteLine("Method_PROTECTED_NoInterfaceRealization"); } // 新增公开暴露方法 public void InvokeProtectedDefaultMethod() { // 需转为接口类型才能访问接口定义的protected成员 (this as ISomeInterface).Method_InterfaceRealization(); } }var instance = new SomeClass(); instance.InvokeProtectedDefaultMethod(); - 方案2:通过派生接口暴露访问入口
代码示例:
调用方式:public interface IDerivedInterface : ISomeInterface { // 派生接口可直接访问父接口的protected成员 public void PublicMethodEntry() => Method_InterfaceRealization(); } // 修改实现类实现派生接口 public class SomeClass: IDerivedInterface { void ISomeInterface.Method1() { Console.WriteLine("Method_PROTECTED_NoInterfaceRealization"); } }IDerivedInterface instance = new SomeClass(); instance.PublicMethodEntry();
问题2:如何在任意位置调用上述代码中的Method1方法
原代码中Method1是接口定义的protected抽象方法,且SomeClass采用显式接口实现,默认无法在外部直接调用,需暴露访问入口:
- 方案1:在实现类中新增公开方法调用
代码示例:
调用方式:public class SomeClass: ISomeInterface { void ISomeInterface.Method1() { Console.WriteLine("Method_PROTECTED_NoInterfaceRealization"); } public void InvokeMethod1() { (this as ISomeInterface).Method1(); } }var instance = new SomeClass(); instance.InvokeMethod1(); - 方案2:通过派生接口暴露
代码示例:
调用方式:public interface IDerivedInterface : ISomeInterface { public void ExposeMethod1() => Method1(); } public class SomeClass: IDerivedInterface { void ISomeInterface.Method1() { Console.WriteLine("Method_PROTECTED_NoInterfaceRealization"); } }IDerivedInterface instance = new SomeClass(); instance.ExposeMethod1();
内容的提问来源于stack exchange,提问作者Владимир В
相关产品推荐
相关产品推荐

