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

Sam*_*Sam 4 c# asp.net-mvc interface

我偶然发现IController并注意到它有一个方法Execute.我的问题是,鉴于ControllerControllerBase哪个实现接口IController,它是ControllerBase如何实现Executeprotected virtual

我的理解是接口必须作为公共方法实现.我对此的理解更加复杂,因为你不能调用Execute实例化的Controller,你必须将它转换为实例IController.

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

要添加多一点,我是知道的显式接口实现,但是如果你查看源代码ControllerBase你将看到的方法,只要实施protected virtual void Execute(RequestContext requestContext)

Mar*_*zek 7

它被称为显式接口实现.

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

阅读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.
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

var instance = new SampleClass();

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

// but can do that:
((IControl)instance).Paint();
Run Code Online (Sandbox Code Playgroud)