c# – 覆盖显式接口实现?

覆盖子类中接口的显式实现的正确方法是什么?
public interface ITest
{
    string Speak();
}

public class ParentTest : ITest
{
    string ITest.Speak()
    {
        return "Meow";
    }
}

public class ChildTest : ParentTest
{
    // causes compile time errors
    override string ITest.Speak()
    {
        // Note: I'd also like to be able to call the base implementation
        return "Mooo" + base.Speak();
    }
}

以上是对语法的最佳猜测,但显然这是错误的.它会导致以下编译时错误

错误CS0621:

`ChildTest.ITest.Speak()’: virtual or abstract members cannot be
private

错误CS0540:

ChildTest.ITest.Speak()': containing type does not implement
interface
ITest’

错误CS0106:

The modifier `override’ is not valid for this item

我实际上可以在不使用显式接口的情况下使用它,所以它实际上并没有阻止我,但我真的想知道,为了我自己的好奇心,如果想用显式接口做这个,那么正确的语法是什么?

解决方法

显式接口实现不能是虚拟成员.请参阅 C# language specification的第13.4.1节(它已过时但在C#6.0中似乎没有更改此逻辑).特别:

It is a compile-time error for an explicit interface member
implementation to include access modifiers,and it is a compile-time
error to include the modifiers abstract,virtual,override,or static.

这意味着,您永远无法直接覆盖此成员.

您可以做的解决方法是从显式实现中调用一个方法

class Base : IBla
{
    void IBla.DoSomething()
    {
        this.DoSomethingForIBla();
    }

    protected virtual void DoSomethingForIBla()
    {
        ...
    }
}

class Derived : Base
{
    protected override void DoSomethingForIBla()
    {
        ...
    }
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...