C# 同一接口继承了好几次

C# 同一接口继承了好几次,c#,.net,inheritance,interface,C#,.net,Inheritance,Interface,例如,我有下面的代码: public interface IFoo1 { void Foo1(); } public interface IFoo2 { void Foo2(); } public interface IOne : IFoo1 { void One(); } public interface IFooList : IFoo1, IFoo2 { } public interface ITwo : IOne, IFooList { } publi

例如,我有下面的代码:

public interface IFoo1
{
    void Foo1();
}

public interface IFoo2
{
    void Foo2();
}

public interface IOne : IFoo1
{
    void One();
}

public interface IFooList : IFoo1, IFoo2
{

}

public interface ITwo : IOne, IFooList
{

}

public class Test : ITwo
{
    public void Foo1()
    {
    }

    public void One()
    {
    }

    public void Foo2()
    {
    }
}
有趣的是,ITwo类从IOne和IFooList继承了IFoo1 twicef,这是一种不好的做法吗?
我使用这些标题只是为了简化。但是我的prod代码中有相同的继承层次结构。拥有这种类型的继承是一个严重的问题吗?

您的继承链中有一个缺陷。如果我们使用一些有意义的名称,就更容易观察到这一点

当前形式的代码:

public interface IAnimal
{
    void Breathe();
}

public interface ILegged
{
    void Stand();
}

public interface IFlyingAnimal : IAnimal
{
    void Fly();
}

public interface ILeggedAnimal : IAnimal, ILegged
{

}

public interface IBird : IFlyingAnimal, ILeggedAnimal
{

}

public class Eagle : IBird
{
    public void Breathe()
    {
        throw new NotImplementedException();
    }

    public void Stand()
    {
        throw new NotImplementedException();
    }

    public void Fly()
    {
        throw new NotImplementedException();
    }
}
正如您所看到的,IBird既是IFlyingAnimal又是ILeggedAnimal,从编译器的角度来看,这很好,但存在重叠,因为它们都是IAnimal

很明显,你需要的是一种被阉割的动物:

这将给你一个合适的继承链


你现在有一只鹰,它是一只伊比利亚鸟,是一种长着翅膀的动物。它能呼吸,能站在腿上还能飞。

为什么它不能继承IOne和IFoo2的遗产呢?IFooList中什么都没有这更像是一个代码审查问题,而不是一个SO问题,但有时这是必要的。然而,它有点代码臭。通常,当你发现自己有继承循环时,是时候重新考虑你的代码结构,看看它为什么循环了。这要看情况而定。您真的想像使用IFoo1或IFoo2一样使用IFooList类吗?或者,这是一种将Foo1和Foo2添加到某些类中的快速而肮脏的方法吗?为什么不从他们的食物中继承呢。如果有一个是一个关系,它不一定是坏的。否则就很糟糕了-快速和肮脏的修复通常是非常糟糕的dirty@maccettura我有更复杂的继承层次结构。这只是一个解释问题的例子。接口就是接口,就像耳机插座、墙上插座、USB插座就是接口一样。如果要在一台设备上安装多个适配器,请向该设备添加多个适配器。您不会尝试创建一个适配器来填充任何电缆、任何电压、任何信号,这是一个很好的示例,但生产代码完全不同@isxaker:这是您的完全相同的代码,具有不同的名称…:-是的,我知道。但我已经提到了它是简化版。无论如何,谢谢
public interface IBird : IFlyingAnimal, ILegged
{

}