为什么 Enumerable 不继承自 IEnumerable
我对这个问题很困惑,无法理解。在 Enumerable
文档中,我读到了这个:
实现 System.Collections.Generic.IEnumerable
以及 Select()
等一些方法会返回 IEnumerable
,我们可以从 Where()< 等其他方法中使用它/code> 使用后。例如:
names.Select(name => name).Where(name => name.Length > 3 );
但 Enumerable
不继承自 IEnumerable
并且 IEnumerable
不会还包含 Select()
、Where()
等...
我错了吗?
或者存在任何原因吗?
I'm very confused about this issue and can't understand it.In the Enumerable
Documentation, I read this:
that implement System.Collections.Generic.IEnumerable
and some methods like Select()
return IEnumerable<TSource>
that we can use from other methods like Where()
after using that.for example:
names.Select(name => name).Where(name => name.Length > 3 );
but Enumerable
doesn't inherit from IEnumerable<T>
and IEnumerable<T>
doesn't contain Select()
,Where()
and etc too...
have i wrong ?
or exists any reason for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Select()、Where() 等是“扩展方法”。它们需要在“其他地方”定义,因为接口无法提供方法的实现。
您可以通过参数列表中的关键字“this”来识别扩展方法。例如:
可以像
IEnumerable
上的一种方法一样使用,并带有一个参数:Func谓词
。The Select(), Where() etc are "extension methods". They need to be defined "elsewhere" as an interface can't supply an implementation of methods.
You can recognize extension methods by the keyword "this" in the argument list. For instance:
can be used as if it's a method on an
IEnumerable<TSource>
with one parameter:Func<TSource, bool> predicate
.正确。但是这句话呢?
根据这句话,我们必须在
IEnumerable
接口中定义方法,并通过继承在Enumerable
类中实现。正确吗?为什么首选扩展方法而不是继承?
Correct.but what about this sentence?
According to this sentence,We have to define methods in the
IEnumerable<T>
interface and implement in theEnumerable
class by inheritance.is it correct?why preferred extension methods against inheritance?
IEnumerable 出现在
IEnumerable
之前,这是一个 2.0+ 接口。IEnumerable came before
IEnumerable<T>
, which is a 2.0+ interface.“为什么首选扩展方法而不是继承?”
Enumerable 是一个静态类,它实现了 IEnumerable 的 50 多个扩展方法。这使您可以在实现 IEnumerable 的类型上使用所有这些扩展方法,而无需强迫程序员为每个集合类型实现所有这些方法。如果 Enumerable 是一个接口而不是静态类,则每个集合类型(例如 List、Dictionary、Set 等)都会有自己的这些扩展方法的实现。
"why preferred extension methods against inheritance?"
Enumerable is a static class that implements over 50 extension methods to IEnumerable. This lets you use all those extension methods on types that implement IEnumerable without forcing the programmers to implement all those methods for each collection type. If Enumerable were an interface instead of a static class, each collection type (such as List, Dictionary, Set, etc) would have its own implementation of these extension methods.
解决此问题的一种方法是使用
Cast()
方法将元素转换为相同类型,该方法返回相同元素的IEnumerable
版本。Rows
的类型为IEnumerable
,转换后它变为IEnumerable
类型,LINQ 扩展方法支持该类型。A way to solve this is by casting the elements to their same type using
Cast<T>()
method, which returns andIEnumerable<T>
version of the same elements.Rows
is of typeIEnumerable
, and after casting it becomes of typeIEnumerable<DataRow>
, which is supported by LINQ extension methods.