1

有什么不同?

class A : IA (IA inherits IB)

对比

class A: IA, IB (IA and IB might have no relation)

IA 和 IB 是接口。

我知道的一个区别:您不需要知道 IB 是否存在于第一个实现中。

4

2 回答 2

2

There is no difference. Remember that you don't have to use either Interface.

It is a design choice. It depends on how you structure your Interfaces.

In your example it might not matter which way you did. Fish:IAqautic, IEatAndSwim forces you to implement behavior (functions) for both interfaces. Here, semantically at-least, IAqautic, IEatAndSwim seem to be similar. We would have to know how they are similar/different to judge the gain/loss of the different design choices.

Assuming that IAqautic and IEatAndSwim are functionally different, then the gain/loss would be in the case that some Object only wants one of the two. Then you can use the one that applies and not have to use the extra functions from the second Interface.

Assuming that IAqautic and IEatAndSwim are functionally similar, then the gain/loss would be in a case where you want both. If IEatAndSwim is a special case of IAqautic then you can have IEatAndSwim extend IAqautic. You only need to use one Interface and your code/intent is clearer.

In short, this question really depends on what is the relationship between the Interfaces. You would use he one that makes the most sense.

于 2013-10-07T03:13:40.343 回答
1

假设我们有一个接口

interface IEat
{
}
interface Swim
{
}

创建鱼时,您会说

class Fish:IEat,ISwim
{
}

您可以创建另一个接口,而不是上述实现:-

 interface IAquatic:IEat,ISwim{}

//在这里,您可以定义更多行为,使其成为水生的,以后可以由您的类使用。

class Fish:IAquatic
{
}

class AnotherAquaticAnimal:IAquatic
{
}

IEat、ISwim 都是可以与人类、水生动物或其他生物相关联的不同行为集,如果有 10 种这样的行为来制作水生动物,您必须在创建任何水生动物时记住并实施所有这些行为。

相反,我们所做的是我们创建和接口 IAquatic 并继承该接口的所有接口,现在您需要记住的是实现这个 IAquatic 接口而不是那 10 个接口,这让您的生活变得轻松。

于 2013-10-03T05:46:05.237 回答