C# · 12月 23, 2021

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
interfaceITest’

错误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() { … }}