为什么IEnumerable上没有ForEach扩展方法? [英] Why is there no ForEach extension method on IEnumerable?

查看:46
本文介绍了为什么IEnumerable上没有ForEach扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

受到另一个问题的启发,询问缺少的 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.

我不希望看到以下内容:

I'd hate to see the following:

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()在编译时(Big Plus!)
  • 调用委托的语法确实简单得多: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.

这些都是许多人在这里提出的要点,我可以理解为什么人们缺少此功能.我不介意Microsoft在下一个框架迭代中添加标准的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆