如何调用基类的显式实现接口的方法 [英] 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; }
}
从 IM的派生类的实现()
,我想调用基类的实现,但我看不出怎么办呢。我试过到目前为止,这是(B类):
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?
更新
我知道这是可能的一个助手的方法可以由派生类中调用,例如:
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.
推荐答案
不幸的是,这是不可能的。结果
甚至不是一个辅助方法。辅助方法有同样的问题,你的第二次尝试:这个
的类型 B
,即使在基类和将调用 M
的实施 B
:
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(); }
}
唯一的解决办法是在 A
一个辅助方法是在 A
使用的执行<$的C $ç> M :
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(); }
}
但是,你需要提供这样也是一种方法 B
是否会有一个 C类:B,I
...
But you would need to provide a method like this also for B
if there will be a class C : B, I
...
这篇关于如何调用基类的显式实现接口的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!