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

前端之家收集整理的这篇文章主要介绍了c# – 覆盖显式接口实现?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
覆盖子类中接口的显式实现的正确方法是什么?
  1. public interface ITest
  2. {
  3. string Speak();
  4. }
  5.  
  6. public class ParentTest : ITest
  7. {
  8. string ITest.Speak()
  9. {
  10. return "Meow";
  11. }
  12. }
  13.  
  14. public class ChildTest : ParentTest
  15. {
  16. // causes compile time errors
  17. override string ITest.Speak()
  18. {
  19. // Note: I'd also like to be able to call the base implementation
  20. return "Mooo" + base.Speak();
  21. }
  22. }

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

错误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.

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

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

  1. class Base : IBla
  2. {
  3. void IBla.DoSomething()
  4. {
  5. this.DoSomethingForIBla();
  6. }
  7.  
  8. protected virtual void DoSomethingForIBla()
  9. {
  10. ...
  11. }
  12. }
  13.  
  14. class Derived : Base
  15. {
  16. protected override void DoSomethingForIBla()
  17. {
  18. ...
  19. }
  20. }

猜你在找的C#相关文章