2012-09-14 63 views
15

可能重複:
Why was IEnumerable<T> made covariant in C# 4?爲什麼IEnumerable的<T>被定義爲IEnumerable <out T>,不IEnumerable的<T>

我正在爲IEnumerable<T>接口定義上MSDN一看,見:

public interface IEnumerable<out T> : IEnumerable 

我想知道爲什麼T被定義爲out,爲什麼不呢?

public interface IEnumerable<T> : IEnumerable 

這是什麼原因?

+0

因爲界面是協變的 – Jodrell

+1

看這裏http://stackoverflow.com/questions/6732299/why-was-ienumerablet-made-covariant-in-c-sharp-4 – Likurg

+0

[Covariance and Contravariance](http:///msdn.microsoft.com/en-us/library/ee207183) – jrummell

回答

20

更多信息可在here找到。

out使得類型參數協變。也就是說,您可以使用該類型或任何派生類型。請注意,out只適用於泛型,它在方法簽名中使用時有不同的含義(儘管您可能已經知道這一點)。

下面是從referenced page採取的示例:

// Covariant interface. 
interface ICovariant<out R> { } 

// Extending covariant interface. 
interface IExtCovariant<out R> : ICovariant<R> { } 

// Implementing covariant interface. 
class Sample<R> : ICovariant<R> { } 

class Program 
{ 
    static void Test() 
    { 
     ICovariant<Object> iobj = new Sample<Object>(); 
     ICovariant<String> istr = new Sample<String>(); 

     // You can assign istr to iobj because 
     // the ICovariant interface is covariant. 
     iobj = istr; 
    } 
} 

正如可以看到,在接口簽名out允許 您到ICovariant<String>分配給ICovariant<Object>變量,StringObject導出。沒有out關鍵字,您將無法執行此操作,因爲類型會有所不同。

你可以閱讀更多關於協方差(和相關的逆變)here

至於其他的答案已經指出,IEnumerable只在.NET 4發協試圖編寫代碼,如:

IEnumerable<Object> strings = new List<string>(); 

將編譯.NET 4.0和更高版本,而不是在以前的版本。

6

Covariance.這允許爲集合分配比其通用參數中指定的更具體或派生類型的項目。

IEnumerable<T>並不總是協變的;這是.NET 4的新功能,其原因是here

0

爲了實現這一點:

class Base {} 
class Derived : Base {} 

List<Derived> list = new List<Derived>(); 
IEnumerable<Base> sequence = list; 
4

out類型參數符表示協方差。

實際上,

如果我定義了兩個接口。

ISomeInterface<T> 
{ 
} 

ISomeCovariantInterface<out T> 
{ 
} 

然後,我實現了他們這樣的。

SomeClass<T> : ISomeInterface<T>, ISomeCovariantInterface<T> 
{ 
} 

然後我嘗試編譯這段代碼,

ISomeCovariantInterface<object> = new SomeClass<string>(); // works 
ISomeInterface<object> = new SomeClass<string>(); // fails 

的是因爲協接口允許更多的衍生情況,那裏的,標準的接口沒有。

+0

+1我認爲這是最清晰的介紹級答案。 – TarkaDaal

相關問題