简体   繁体   中英

Is it possible to call the explicit interface implementation of the base class in c#?

I would like this program to compile, and then print the output below:

public interface IFoo
{
    void Bar();
}

public class FooBase : IFoo
{
    void IFoo.Bar()
    {
        Console.WriteLine("Hello from base class.");
    }
}

public class Foo : FooBase, IFoo
{
    void IFoo.Bar()
    {
        (base as IFoo).Bar(); // doesn't compile
        Console.WriteLine("Foo added some behavior!");
    }
}

public static class Program
{
    public static void Main(string[] args)
    {
        var foo = new Foo() as IFoo;
        foo.Bar();
    }
}

Desired output:

Hello from base class.
Foo added some behavior!

Obviously, the code above doesn't compile, because it's an invalid way to use the base keyword. Is there a way to accomplish this, without changing the implementation in the base class to a non-explicit one?

You can simply have the explicit interface implementation in the base class call a protected method in the class for its implementation. This allows other derived classes to still call that protected method while still explicitly implementing the interface (and also not publicly exposing the interface's method through the type itself, which presumably is the actual goal).

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