繁体   English   中英

如何在子接口中提供默认实现?

[英]How do I provide a default implementation in a child interface?

如果我有一个接口IExampleInterface

interface IExampleInterface {
    int GetValue();
}

有没有办法在子接口中为GetValue()提供默认实现? IE:

interface IExampleInterfaceChild : IExampleInterface {
    // Compiler warns that we're just name hiding here. 
    // Attempting to use 'override' keyword results in compiler error.
    int GetValue() => 123; 
}

经过更多的实验,我找到了以下解决方案:

interface IExampleInterfaceChild : IExampleInterface {
    int IExampleInterface.GetValue() => 123; 
}

使用您为其提供实现的方法的接口的名称是正确的答案(即IParentInterface.ParentMethodName() =>... )。

我使用以下代码测试了运行时结果:

class ExampleClass : IExampleInterfaceChild {
        
}

class Program {
    static void Main() {
        IExampleInterface e = new ExampleClass();

        Console.WriteLine(e.GetValue()); // Prints '123'
    }
}

在 C# 8.0+ 中,接口可以有一个默认方法:

https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods

否则,如果由于使用 .Net Framework 而在 C# 上使用较低版本,则可以使用抽象 class。 但是如果您希望您的类能够实现多个接口,则此选项可能不适合您:

public abstract class ExampleInterfaceChild : IExampleInterface {
    int GetValue() => 123; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM