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

如何在子界面中提供默认实现?

如何解决如何在子界面中提供默认实现?

如果我有一个接口 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; 
}

解决方法

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

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

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