为什么 IEnumerable 上没有 ForEach 扩展方法? [英] Why is there no ForEach extension method on IEnumerable?
问题描述
受到另一个关于缺少 Zip
函数的问题的启发:
Inspired by another question asking about the missing Zip
function:
为什么IEnumerable
接口上没有ForEach
扩展方法?或者任何地方?获得 ForEach
方法的唯一类是 List<>
.是否有丢失的原因,也许是性能?
Why is there no ForEach
extension method on the IEnumerable
interface? Or anywhere? The only class that gets a ForEach
method is List<>
. Is there a reason why it's missing, maybe performance?
推荐答案
在大多数情况下,该语言中已经包含了一个 foreach
语句.
There is already a foreach
statement included in the language that does the job most of the time.
我不想看到以下内容:
list.ForEach( item =>
{
item.DoSomething();
} );
代替:
foreach(Item item in list)
{
item.DoSomething();
}
后者更清晰、更易于阅读在大多数情况下,尽管键入时间可能会更长一些.
The latter is clearer and easier to read in most situations, although maybe a bit longer to type.
但是,我必须承认我在这个问题上改变了立场;ForEach()
扩展方法在某些情况下确实很有用.
However, I must admit I changed my stance on that issue; a ForEach()
extension method would indeed be useful in some situations.
以下是语句和方法之间的主要区别:
Here are the major differences between the statement and the method:
- 类型检查:foreach 在运行时完成,
ForEach()
在编译时(大加分!) - 调用委托的语法确实要简单得多:objects.ForEach(DoSomething);
- ForEach() 可以被链接起来:尽管这样一个功能的邪恶/有用性是可以讨论的.
- Type checking: foreach is done at runtime,
ForEach()
is at compile time (Big Plus!) - The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething);
- ForEach() could be chained: although evilness/usefulness of such a feature is open to discussion.
这些都是这里很多人提出的重要观点,我可以理解为什么人们缺少该功能.我不介意微软在下一次框架迭代中添加一个标准的 ForEach 方法.
Those are all great points made by many people here and I can see why people are missing the function. I wouldn't mind Microsoft adding a standard ForEach method in the next framework iteration.
这篇关于为什么 IEnumerable 上没有 ForEach 扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!