Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

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

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
{
  int I.M() { return 1; }
}

class B : A, I
{
  int I.M() { return 2; }
}

From the derived class' implementation of I.M(), I'd like to call the implementation of the base class, but I don't see how to do it. What I tried so far is this (in class B):

int I.M() { return (base as I).M() + 2; }
// this gives a compile-time error
//error CS0175: Use of keyword 'base' is not valid in this context

int I.M() { return ((this as A) as I).M() + 2; }
// this results in an endless loop, since it calls B's implementation

Is there a way to do this, without having to implement another (non interface-explicit) helper method?


Update:

I know it's possible with a "helper" method which can be called by the derived class, e.g:

class A : I
{
    int I.M() { return M2(); }
    protected int M2 { return 1; }
}

I can also change it to implement the interface non-explicitly. But I was just wondering if it's possible without any of these workarounds.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...