问题描述
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;
}
解决方法
经过多次实验,我找到了以下解决方案:
else
使用您为其提供实现的方法的接口的名称是正确的答案(即 interface IExampleInterfaceChild : IExampleInterface {
int IExampleInterface.GetValue() => 123;
}
)。
我使用以下代码测试了运行时结果:
IParentInterface.ParentMethodName() => ...
,
在 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;
}