gpt4 book ai didi

c# - C#接口(interface)方法的默认实现?

转载 作者:IT王子 更新时间:2023-10-29 04:10:23 25 4
gpt4 key购买 nike

是否可以在 C# 中定义一个具有默认实现的接口(interface)? (这样我们就可以定义一个实现该接口(interface)的类,而无需实现该特定的默认方法)。

我知道扩展方法(例如 this link 中的解释)。但这不是我的答案,因为有如下方法扩展,编译器仍然提示在 MyClass 中实现 MyMethod:

public interface IMyInterface
{
string MyMethod();
}

public static class IMyInterfaceExtens
{
public static string MyMethod(this IMyInterface someObj)
{
return "Default method!";
}
}

public class MyClass: IMyInterface
{
// I want to have a default implementation of "MyMethod"
// so that I can skip implementing it here
}

我问这个是因为(至少据我所知)可以在 Java 中这样做(参见 here)。

PS:拥有一个带有某种方法的抽象基类不是我的答案,因为我们在 C# 中没有多重继承,它不同于拥有一个接口(interface)的默认实现(如果可能!)。

最佳答案

C# v8 及更高版本也允许在接口(interface)中实现具体方法。这将使您的具体实现类在您将来更改正在实现的接口(interface)时不会中断。

所以这样的事情现在是可能的:

interface IA
{
void NotImplementedMethod(); //method having only declaration
void M()
{
WriteLine("IA.M");
}//method with declaration + definition
}

请引用这个GitHub issue # 288 . Mads Torgersen 在 this 中也详细讨论了此功能。第 9 channel 视频。

MS 文档 - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods

关于c# - C#接口(interface)方法的默认实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30322008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com