How to call an explicitly implemented interface-method on the base class

后端 未结 7 1197
死守一世寂寞
死守一世寂寞 2020-12-05 09:56

I have a situation, where two classes (one deriving from the other) both implement the same interface explicitly:

interface I
{
  int M();
}

class A : I
{
          


        
7条回答
  •  长情又很酷
    2020-12-05 10:26

    Unfortunately, it isn't possible.
    Not even with a helper method. The helper method has the same problems as your second attempt: this is of type B, even in the base class and will call the implementation of M in B:

    interface I
    {
      int M();
    }
    class A : I
    {
      int I.M() { return 1; }
      protected int CallM() { return (this as I).M(); }
    }
    class B : A, I
    {
      int I.M() { return CallM(); }
    }
    

    The only workaround would be a helper method in A that is used in A's implementation of M:

    interface I
    {
      int M();
    }
    class A : I
    {
      int I.M() { return CallM(); }
      protected int CallM() { return 1; }
    }
    class B : A, I
    {
      int I.M() { return CallM(); }
    }
    

    But you would need to provide a method like this also for B if there will be a class C : B, I...

提交回复
热议问题