2016-05-10 83 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