2010-06-09 70 views
3

繼承了我對這個問題很迷茫,不明白it.In的Enumerable文檔,我這樣說的:可枚舉爲什麼不自IEnumerable <T>

實現System.Collections.Generic。 IEnumerable的

和一些方法,如Select()回報IEnumerable<TSource>,我們可以使用that.for例子之後,從其他方法使用像Where()

names.Select(name => name).Where(name => name.Length > 3); 

Enumerable不會IEnumerable<T>IEnumerable<T>繼承不含Select()Where()和等太...

有我錯了嗎?
或存在這種情況的任何原因?

回答

8

Select(),Where()等是「extension methods」。他們需要被定義爲「別處」,因爲接口不能提供方法的實現。

您可以通過參數列表中的關鍵字「this」識別擴展方法。例如:

public static IEnumerable<TSource> Where<TSource>(
    this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate 
) 

可以用作是否與一個參數上的IEnumerable<TSource>的方法:Func<TSource, bool> predicate

0

Correct.but怎麼樣這句話?

實現System.Collections.Generic.IEnumerable

根據這句話,我們必須通過inheritance.is它正確的定義在IEnumerable<T>接口方法並實現在Enumerable類?

爲什麼首選擴展方法反對繼承?

+2

請注意,您應該添加註釋或編輯您的問題,而不是創建新的答案來添加新的信息或問題。 – OregonGhost 2010-06-09 13:58:50

0

IEnumerable在IEnumerable<T>之前,這是一個2.0 +接口。

0

「爲什麼首選擴展方法反對繼承?」

Enumerable是一個靜態類,它爲IEnumerable實現了50多種擴展方法。這使您可以在實現IEnumerable的類型上使用所有這些擴展方法,而無需強制程序員爲每個集合類型實現所有這些方法。如果Enumerable是一個接口而不是一個靜態類,那麼每個集合類型(如List,Dictionary,Set等)都有自己的這些擴展方法的實現。

0

解決此問題的一種方法是通過使用Cast<T>()方法將元素投射到相同類型的方法,該方法返回與IEnumerable<T>版本相同的元素。

DataTable dt = ... 
dt.Rows.Cast<DataRow>().Where()... 

RowsIEnumerable型的,並且在鑄造後變得IEnumerable<DataRow>類型,這是由LINQ擴展方法支持的。

相關問題