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

cri*_*ito 4 c#

我试图调用在基类上实现的显式实现的接口方法,但似乎无法让它工作.我同意这个想法是丑陋的,但我已经尝试了我能想到的每一个组合,但无济于事.在这种情况下,我可以改变基类,但我想我会问这个问题是为了满足我的普遍好奇心.

有任何想法吗?

// 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"
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 7

你不能(它不是子类可用的接口的一部分).在那种情况下,使用类似的东西:

// base class
bool MyInterface.DoSomething()
{
    return DoSomething();
}
protected bool DoSomething() {...}
Run Code Online (Sandbox Code Playgroud)

那么任何子类都可以调用protected DoSomething(),或者(更好):

protected virtual bool DoSomething() {...}
Run Code Online (Sandbox Code Playgroud)

现在它可以覆盖而不是重新实现接口:

public class DerivedClass : BaseClass
{
    protected override bool DoSomething()
    {
        // changed version, perhaps calling base.DoSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有没有特别的理由为什么C#不能支持`((IInterface)base``如果VB.NET可以?当您向不属于您的代码的库添加功能时,它会很有用.唯一的其他选项是反射和包装第二个基类实例.保持两个实例同步可能是一场噩梦. (3认同)