如何调用显式实现接口方法的基类实现?

5
我试图调用基类上实现的显式接口方法,但似乎无法使其正常工作。我同意这个想法很丑陋,但我已尝试了我所能想到的所有组合,但都没有成功。在这种情况下,我可以更改基类,但我还是想提出问题来满足我的好奇心。
有什么想法吗?
// example interface
interface MyInterface
{
    bool DoSomething();
}

// BaseClass explicitly implements the interface
public class BaseClass : MyInterface
{
    bool MyInterface.DoSomething()
    {
    }
}

// Derived class 
public class DerivedClass : BaseClass
{
    // Also explicitly implements interface
    bool MyInterface.DoSomething()
    {
        // I wish to call the base class' implementation
        // of DoSomething here
        ((MyInterface)(base as BaseClass)).DoSomething(); // does not work - "base not valid in context"
    }
}
1个回答

7

您不能这样做(因为它不是可供子类使用的接口的一部分)。在这种情况下,可以使用以下内容:

// base class
bool MyInterface.DoSomething()
{
    return DoSomething();
}
protected bool DoSomething() {...}

然后任何子类都可以调用受保护的DoSomething(),或者(更好的方法):

protected virtual bool DoSomething() {...}

现在它只需要覆盖而不是重新实现接口:
public class DerivedClass : BaseClass
{
    protected override bool DoSomething()
    {
        // changed version, perhaps calling base.DoSomething();
    }
}

@cristobalito 顺便说一下...你可以在VB.NET中更直接地实现这一点;然而,这并不足以理由去切换语言;p - Marc Gravell
不可能发生那种事情,马克! - cristobalito
3
为什么 C# 不能像 VB.NET 一样支持 ((IInterface)base)?这对于向一个你没有所有代码的库添加功能很有帮助。另外的选项是使用反射和包装第二个基类实例,但要保持这两个实例同步可能会非常困难。 - jnm2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接