繁体   English   中英

如何将接口实现为受保护的方法?

[英]How is it possible to have an interface implemented as a protected method?

我偶然发现了IController并注意到它有一个方法Execute 是,鉴于我的问题是Controller派生自ControllerBase它实现了接口IController ,它是如何ControllerBase可以实现Execute作为protected virtual

我的理解是接口必须作为公共方法实现。 我对此的理解更加复杂,因为您无法在实例化的Controller上调用Execute ,而必须将其转换为IController的实例。

如何将接口实现为受保护的方法?

要添加更多内容,我知道显式接口实现,但是如果您查看 ControllerBase 的源代码 ,您将看到该方法实现为protected virtual void Execute(RequestContext requestContext)

它被称为显式接口实现。

实现接口的类可以显式实现该接口的成员。 显式实现成员时,不能通过类实例访问它,而只能通过接口的实例访问它

阅读MSDN: 显式接口实现教程

简单样本:

interface IControl
{
    void Paint();
}

public class SampleClass : IControl
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }

    protected void Paint()
    {
        // you can declare that one, because IControl.Paint is already fulfilled.
    }
}

用法:

var instance = new SampleClass();

// can't do that:
// instance.Paint();

// but can do that:
((IControl)instance).Paint();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM