微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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()
    {
        ...
    }
}

原文地址:https://www.jb51.cc/csharp/91800.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐