在 C# 8 后来,我们有 default interface methods , 所以:
这不是破坏的原则吗?接口(interface) ?
我们什么时候应该使用默认接口(interface)方法而不是 基础(抽象)类 ?
最佳答案
为什么我们有接口(interface)?
从理论上讲,接口(interface)实现和类继承都解决了相同的问题:它们允许您定义 subtype relationship类型之间。
那么为什么我们在 C# 中两者都有呢?为什么我们需要接口(interface)?我们不能像在 C++ 中那样将接口(interface)定义为抽象类吗?
原因是the diamond problem : ( Image source )
如果两者都是 B
和 C
实现A.DoSomething()
不同,应该采用哪种实现方式 D
继承?这是一个难题,Java 和 C# 设计者决定通过只允许不包含任何实现的特殊基类型的多重继承来避免它。他们决定将这些特殊的基本类型称为 接口(interface) .
所以,没有“接口(interface)原则”。接口(interface)只是解决特定问题的“工具”。
那么为什么我们需要默认实现呢?
向后兼容性。您编写了一个非常成功的库,全世界成千上万的开发人员都在使用它。您的库包含一些接口(interface)I
,现在您决定需要一个额外的方法 M
在上面。问题是:
M
至I
,因为这会破坏现有的实现 I
的类(因为他们没有实现 M
)和 I
到一个抽象基类,因为那样也会破坏现有的实现 I
的类。 ,并且您将失去进行多重继承的能力。 那么默认实现如何避免菱形问题呢?
通过不继承这些默认方法(示例受 this article 中的启发,请参阅完整文章了解一些有趣的极端案例):
interface I1
{
void M() { Console.WriteLine("I1.M"); } // default method
}
interface I2
{
void M() { Console.WriteLine("I2.M"); } // default method
}
class C : I1, I2 { }
class Program
{
static void Main(string[] args)
{
// c, i1 and i2 reference the same object
C c = new C();
I1 i1 = c;
I2 i2 = c;
i1.M(); // prints "I1.M"
i2.M(); // prints "I2.M"
c.M(); // compile error: class 'C' does not contain a member 'M'
}
}
关于c# - 我们什么时候应该在 C# 中使用默认接口(interface)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62832992/