2016-05-10 68 views
6

我对C#中接口的继承语法有点不清楚。在C中声明接口继承#

例如:

public interface IFoo 
{ 
} 
public interface IBar : IFoo 
{ 
} 

是什么这之间的区别:

public interface IQux : IBar 
{ 
} 

这:

public interface IQux : IBar, IFoo 
{ 
} 

或者,对于现实世界的例子,为什么ICollection<T>宣布像这样:

public interface ICollection<T> : IEnumerable<T>, IEnumerable 

,而不是这样的:

public interface ICollection<T> : IEnumerable<T> 

因为IEnumerable<T>已经从IEnumerable继承?

+0

它是一个很好的问题 –

+1

没有必要明确列出基础接口已实施,但它很好的清晰。 IOW,没有功能差异。 – Blorgbeard

+0

赞同@Blorgbeard,没有什么区别,只是为了清晰起见 –

回答

5

埃里克利珀解释了它在很好的这篇文章:

https://blogs.msdn.microsoft.com/ericlippert/2011/04/04/so-many-interfaces

如果从IFooIBar继承,然后,从编译器的角度来看,没有什么区别介于:

public interface IQux : IBar 
{ 
} 

这:

public interface IQux : IBar, IFoo 
{ 
} 

您可以选择指出IQux结合IFoo,如果你认为它使代码更易读。或者你可以选择不。从C#规范

2

泛型并没有从一开始就存在 - 看看C#1.0的文档,你将不会看到IEnumerable<T>.

关于第一个问题:没有区别(甚至不显式接口实现尽可能我可以告诉)。

求索这样的:

public interface IFoo 
{ 
    void M(); 
} 

public interface IBar : IFoo { } 
public interface IQux : IBar, IFoo { } 
public interface IQux2 : IBar { } 

// Both work: 
// class X : IQux 
class X : IQux2 
{ 
    void IFoo.M() { } 
} 
+0

^^他说了什么。虽然我认为它有时候会涉及到你想如何使用你的接口。你可能想要执行一个实现IBar的类来实现IFoo。或者也许有一些IFoo对IBar没有意义。我认为这真的归结于你*想要从你的界面中获得什么,以及*你打算如何使用它们或者它们是如何相互关联的。 –

1

相关报价(版本5),13.4节:

的类或结构直接实现的接口也直接实现该接口的所有基本接口的隐式。即使类或结构未明确列出基类列表中的所有基接口,情况也是如此。

因此,不需要明确列出基本接口。我认为这只是为了澄清开发者。

+0

@xandercoded多态性的好处是什么? – DavidG

+0

@xandercoded您应该取消删除其中一个答案并编辑以解释您的意思。不相关答案的评论部分不是这个地方。 – Blorgbeard

+0

而你似乎仍然忽略了一点:没有必要声明ICollection从IEnumerable继承,因为它继承自'IEnumerable ',它从IEnumerable继承。所以无论你是否声明它,它都从'IEnumerable'继承。问题不是它为什么应该这样做,而是关于所需的语法。 – Blorgbeard