【问题标题】:Is diamond problem with interfaces in C# possible?C# 中的接口是否可能出现钻石问题?
【发布时间】:2018-10-08 07:47:11
【问题描述】:

下面的代码是否存在架构问题?所谓的diamond problem 是否可能存在接口或类似问题?

interface IComponent
{
    void DoStuff();
}

interface ITitledComponent : IComponent
{
    string Title { get; }
}

abstract class ComponentBase : IComponent
{
    public void DoStuff()
    {
        throw new NotImplementedException();
    }
}

class MyComponent : ComponentBase, ITitledComponent
{
    public string Title => throw new NotImplementedException();
}

当然,类的菱形继承是一个糟糕的决定,这在 C# 中是不可能的。但是关于接口我没有找到资料。

【问题讨论】:

  • 我的理解是对的,通常称为"diamond problem"。当然,纯接口不用担心,因为它们没有实现。
  • 这被称为“钻石问题”。抱歉术语错误。 en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem
  • 钻石问题是关于类而不是接口,你不能在 C# 中拥有它,因为你不能继承超过 1 个类
  • @R.Savelyev:乍一看,您不需要从IComponent 继承ITitledComponent。有什么理由这样做吗?
  • 如果ITitledComponentComponentBase 都提供了DoStuff实现IComponentMyComponent 没有,那应该是钻石问题。但是由于接口不能提供实现,所以这不是钻石问题。即使接口的默认实现出现(可能在 c# 8 中),也不会产生菱形问题。

标签: c# inheritance interface abstract-class


【解决方案1】:

不,C# 不可能产生菱形问题,因为您只能从一个类继承。接口不是继承的,而是实现的。因此,编译器和编码器的实际问题是永远不会发生一个方法的两个实现并且不知道为特定类选择哪个实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多