【问题标题】:How do I provide a default implementation in a child interface?如何在子接口中提供默认实现?
【发布时间】:2026-01-13 10:35:01
【问题描述】:

如果我有接口IExampleInterface:

interface IExampleInterface {
    int GetValue();
}

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

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

【问题讨论】:

  • 接口不包含任何代码。
  • @TaW 他们在最新版本的 c# 中做。许多人认为这是一个糟糕的设计选择,但这是一个见仁见智的问题。 @Xenoprimate 你试过new int GetValue() => 123;吗?
  • 嗯,很有趣,虽然很违反直觉。但是事情往往会在一个人身上成长.. ;-)

标签: c# c#-8.0 default-interface-member


【解决方案1】:

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

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'
    }
}

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 这没有回答问题。问题是询问如何/是否可以在接口中为父接口中的接口成员提供默认实现。
    • @Xenoprimate 是的,文档的链接就是答案。