覆盖子类中接口的显式实现的正确方法是什么?
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(); } }
以上是对语法的最佳猜测,但显然这是错误的.它会导致以下编译时错误:@H_404_5@
`ChildTest.ITest.Speak()’: virtual or abstract members cannot be
private@H_404_5@
ChildTest.ITest.Speak()': containing type does not implement
ITest’@H_404_5@
interface
The modifier `override’ is not valid for this item@H_404_5@
我实际上可以在不使用显式接口的情况下使用它,所以它实际上并没有阻止我,但我真的想知道,为了我自己的好奇心,如果想用显式接口做这个,那么正确的语法是什么?@H_404_5@
解决方法
显式接口实现不能是虚拟成员.请参阅
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.@H_404_5@
这意味着,您永远无法直接覆盖此成员.@H_404_5@
您可以做的解决方法是从显式实现中调用另一个虚方法:@H_404_5@
class Base : IBla { void IBla.DoSomething() { this.DoSomethingForIBla(); } protected virtual void DoSomethingForIBla() { ... } } class Derived : Base { protected override void DoSomethingForIBla() { ... } }