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

Xen*_*ate 2 c# c#-8.0 default-interface-member

如果我有一个界面IExampleInterface

interface IExampleInterface {
    int GetValue();
}
Run Code Online (Sandbox Code Playgroud)

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; 
}
Run Code Online (Sandbox Code Playgroud)

Xen*_*ate 5

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

interface IExampleInterfaceChild : IExampleInterface {
    int IExampleInterface.GetValue() => 123; 
}
Run Code Online (Sandbox Code Playgroud)

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

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

class ExampleClass : IExampleInterfaceChild {
        
}

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

        Console.WriteLine(e.GetValue()); // Prints '123'
    }
}
Run Code Online (Sandbox Code Playgroud)