为什么Enumerable没有继承自IEnumerable<T>?

3

我对这个问题很困惑,无法理解。在Enumerable文档中,我读到了这样的内容:

实现System.Collections.Generic.IEnumerable接口的类

一些方法,例如Select()返回IEnumerable<TSource>,我们可以在使用它之后从其他方法中使用Where()。例如:

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

但是Enumerable没有从IEnumerable<T>继承,IEnumerable<T>也不包含Select()Where()等方法……

我错了吗?还是有任何原因呢?

6个回答

8
Select()、Where()等方法是“扩展方法”。它们需要在“其他地方”定义,因为接口不能提供方法的实现。
你可以通过参数列表中的关键字“this”来识别扩展方法。例如:
public static IEnumerable<TSource> Where<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate
)

可以像对一个带有一个参数的 Func<TSource, bool> predicateIEnumerable<TSource> 方法一样使用。


0
一种解决方法是通过使用Cast<T>()方法将元素强制转换为它们相同的类型,该方法返回相同元素的IEnumerable<T>版本。
DataTable dt = ...
dt.Rows.Cast<DataRow>().Where()...

RowsIEnumerable 类型的,经过转换后变成了 IEnumerable<DataRow> 类型,这种类型支持 LINQ 扩展方法。


0

正确。但这句话怎么样?

实现 System.Collections.Generic.IEnumerable 接口

根据这个句子,我们必须在 IEnumerable<T> 接口中定义方法,并通过继承在 Enumerable 类中实现。是吗?

为什么更喜欢使用扩展方法而不是继承?


2
请注意,您应该添加注释或编辑您的问题,而不是创建新的答案以添加新的信息或问题。 - OregonGhost

0

IEnumerable<T>是2.0+接口,而在它之前有IEnumerable。


0
"

为什么更喜欢使用扩展方法而不是继承?

Enumerable是一个静态类,实现了50多个IEnumerable的扩展方法。这使得您可以在实现IEnumerable的类型上使用所有这些扩展方法,而无需强制程序员为每种集合类型实现所有这些方法。如果Enumerable是一个接口而不是一个静态类,那么每种集合类型(例如List、Dictionary、Set等)都将有自己的这些扩展方法实现。

"

-2

这是关于扩展方法,而不是迭代器块。 - thecoop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接