c# - 为什么 Enumerable 不继承自 IEnumerable<T>

标签 c# linq ienumerable enumerable

我对这个问题很困惑,看不懂。在Enumerable文档,我读过这个:

that implement System.Collections.Generic.IEnumerable

还有一些方法,比如 Select()返回 IEnumerable<TSource>我们可以使用其他方法,如 Where()使用那个之后。例如:

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

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

我错了吗?
或者有什么原因吗?

最佳答案

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

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

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

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

关于c# - 为什么 Enumerable 不继承自 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3004341/

相关文章:

c# - 从动态列表中获取唯一的值列表

c# - 在一行中创建 IEnumerable 并将其传递给方法

c# - 发现重复符号 'WixAction:InstallExecuteSequence/RemoveExistingProducts'。这通常意味着 ID 重复

c# - 如何转换日期 dd/mm/yyyy hh :mm:ss AM to mm/dd/yyyy hh:mm:ss: am throwing invalid cast exception

C# 日期时间小时分钟验证

c# - 如何按 double 值对 List<T> 进行排序?

c# - 如何使用 orderbydescending 在 linq 中查询?

c# - 从字典中获取键值对

c# - IEnumerable 集合在 WCF 传输时被清除

c# - 如何在 C# 中从 DataRow 获取 DateTime 值