How to call the base interface implementation when derived classes re-implement the interface?

StackOverflow https://stackoverflow.com/questions/23393329

Frage

So, for one reason or another, I'm testing the limits of C# and the .NET VM. I came across a bit of perplexing behavior.

Take these classes and interfaces:

public interface ITest
{
    void Test();
    void Test2();
}
public abstract class Base : ITest
{
    void ITest.Test()
    {
        Console.WriteLine("base");
    }
    public void Test2()
    {
        Console.WriteLine("base2");
    }
    public void Test3()
    {
        Console.WriteLine("base3");
    }
}
public class Impl : Base, ITest
{
    void ITest.Test()
    {
        Console.WriteLine("impl");
    }
    void ITest.Test2()
    {
        Console.WriteLine("impl2");
    }
    public void Test3()
    {
        Console.WriteLine("impl3");
    }
}

And then use them like so:

        var i = new Impl();
        var b = (Base)i;
        var itest1 = (ITest)i;
        var itest2 = (ITest)b;
        itest1.Test();
        itest2.Test();
        itest1.Test2();
        itest2.Test2();
        i.Test2();
        b.Test2();
        i.Test3(); //for reference, a standard non-virtual method outside of an interface
        b.Test3();

I expected for the output to look something like so:

impl
base
impl2
base2
impl2
base2
impl3
base3

But of course, things can't be that simple. So, the actual output is this:

impl
impl
impl2
impl2
base2
base2
impl3
base3

Beyond this crazy weird behavior, is it possible to access the Base.Test() implementation?

War es hilfreich?

Lösung

Maybe you should check why you find the results you get weird. To me it looks like you got exactly what you implemented.

There is no way to get Base.Test because there is no Base.Test. You need to access this through the interface explicitly and then it's no longer Base, but Impl, because the underlying real object is not of type Base.

Andere Tipps

Base is explicitly implementing ITest.Test(). It's an implementation, but it's a "private" implementation, only accessible through the ITest interface.

On top of that, Impl is re-implementing ITest.Test(), so when you try your itest2.Test() you are going to point to this later re-implementation.

The 2 key points here are:

  1. There is no public Base.Test().
  2. You killed all your possibilities of accessing the ITest.Test() implementation on Base by re-implementing it on Impl.

Re-implementation, re-implementation, re-implementation.

May I suggest renaming the question slightly: How to call the base interface explicit implementation when derived classes explicit re-implement the interface? Because that's what you are asking...

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top