相同的接口继承了几次

时间:2018-02-16 15:04:15

标签: 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
{

}

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

    public void One()
    {
    }

    public void Foo2()
    {
    }
}

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

1 个答案:

答案 0 :(得分:1)

您的继承链存在缺陷。如果我们应用一些有意义的名称,就可以更容易地观察到这一点。

您当前形式的代码:

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,从编译器的角度来看很好,但是有重叠,因为它们都是{{1} }。

显然,您需要的是IAnimal IFlyingAnimal

ILegged

这将为您提供适当的继承链。

您现在拥有的public interface IBird : IFlyingAnimal, ILegged { } EagleIBirdIFlyingAnimalILegged。它的腿部可以BreatheStandFly