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.
Here is my version of Roland Pihlakas's nice solution. This version supports the entire inheritance chain instead of immediate base class. The Invoke method includes additional parameters and there is a void type Invoke for non-function methods.
It is possible using reflection.
The code follows. I added caching as a basic optimization, but it can be optimized further by using
Delegate.CreateDelegate
onmethodInfo
. Also, parameter count and type checks can be added usingmethodInfo.GetParameters()
.Here is the source of my inspiration.
it is necessary explicitly?... Can you use an abstract class or class instead of interface?
http://msdn.microsoft.com/en-us/library/hfw7t1ce(v=vs.71).aspx
I have no idea its not possible call base method when it comes from implementation of interface.
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 typeB
, even in the base class and will call the implementation ofM
inB
:The only workaround would be a helper method in
A
that is used inA
's implementation ofM
:But you would need to provide a method like this also for
B
if there will be aclass C : B, I
...You can't call Explicit interface method in base class,here i solved this issue
I have two interface -> Interface1 and Interface2
Main class Method
and my interface implemented class