简体   繁体   中英

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

I just stumbled across IController and noticed that it has a method Execute . My question is that given that Controller derives from ControllerBase which implements the interface IController , how is it that ControllerBase can implement Execute as protected virtual ?

My understanding is that an interface must be implemented as a public method. My understanding of this is further complicated as you can't call Execute on an instantiated Controller and you must instead cast it to an instance of IController .

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

To add a bit more, I know about explicit interface implementation, however if you view the source code for ControllerBase at you will see that the method is implemented as protected virtual void Execute(RequestContext requestContext)

It's called explicit Interface Implementation.

A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface .

Read more on MSDN: Explicit Interface Implementation Tutorial .

Simple sample:

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.
    }
}

And usage:

var instance = new SampleClass();

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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