3

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

实现 System.Collections.Generic.IEnumerable

还有一些方法,比如Select()returnIEnumerable<TSource>我们可以从其他方法中使用,比如Where()在使用 that.for 之后:

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

Enumerable不继承IEnumerable<T>也不IEnumerable<T>包含Select(),Where()等等...

我错了吗?
或存在任何理由吗?

4

6 回答 6

8

Select()、Where() 等是“扩展方法”。它们需要在“其他地方”定义,因为接口不能提供方法的实现。

您可以通过参数列表中的关键字“this”来识别扩展方法。例如:

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

可以像使用IEnumerable<TSource>一个参数的方法一样使用:Func<TSource, bool> predicate.

于 2010-06-09T08:59:03.793 回答
0

正确。但是这句话呢?

实现 System.Collections.Generic.IEnumerable

按照这句话,我们要在IEnumerable<T>接口中定义方法,在Enumerable类中通过继承来实现。对吗?

为什么首选扩展方法来反对继承?

于 2010-06-09T13:16:36.653 回答
0

“为什么首选扩展方法来反对继承?”

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

于 2014-04-29T18:35:41.717 回答
0

IEnumerable 出现在IEnumerable<T>2.0+ 接口之前。

于 2010-06-09T13:21:44.457 回答
0

解决这个问题的一种方法是使用Cast<T>()方法将元素转换为相同的类型,该方法返回IEnumerable<T>相同元素的版本。

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

Rows是 type IEnumerable,并且在转换之后变成 type IEnumerable<DataRow>,这是 LINQ 扩展方法支持的。

于 2016-03-11T06:59:47.200 回答
-2

我曾说过您还阅读了 Jon Skeet撰写的这篇文章Iterators, iterator blocks and data pipelines以获得进一步的见解

于 2010-06-09T09:02:17.813 回答