c# – 为什么只有ForEach方法的列表

c# – 为什么只有ForEach方法的列表,第1张

概述从我可以看到,ForEach方法仅适用于列表 class. 这是为什么?我可以看到没有任何理由ForEach不可用于实现IEnumerable / IEnumerator接口的任何类,如果您需要执行一个小动作(1行比1行2样板Foreach语法更可读),这是一个非常有用的方法. ..). 更新:我会澄清我的问题.包含ForEach的序列有完全有效的原因.没有包括所有序列的完美的理由. 但是我不明白 从我可以看到,ForEach方法仅适用于列表 class.

这是为什么?我可以看到没有任何理由ForEach不可用于实现IEnumerable / IEnumerator接口的任何类,如果您需要执行一个小动作(1行比1行2样板Foreach语法更可读),这是一个非常有用的方法. ..).

更新:我会澄清我的问题.包含ForEach的序列有完全有效的原因.没有包括所有序列的完美的理由.

但是我不明白为什么ForEach只能包含在一些序列中.

解决方法 见Eric lippert的帖子: “foreach” vs “ForEach”

A number of people have asked me why
there is no Microsoft-provIDed
“ForEach” sequence operator extension
method. The List class has such a
method already of course,but there’s
no reason why such a method Could not
be created as an extension method for
all sequences.

But we can go a bit deeper here. I am
philosophically opposed to provIDing
such a method,for two reasons.

The first reason is that doing so
violates the functional programming
principles that all the other sequence
operators are based upon. Clearly the
sole purpose of a call to this method
is to cause sIDe effects.

The second reason is that doing so
adds zero new representational power
to the language.

Well,the VS Languages team does not have any influence on what goes into List. I personally find the “ForEach” method on List philosophically troubling for all the same reasons that I would find an extension method on IEnumerable troubling. (And the VSL team does control that.) The one mitigating factor is that List is clearly designed to be a mutable,not-sIDe-effect-free data structure,so using Expressions that mutate it seems slightly less bad. — Eric

总结

以上是内存溢出为你收集整理的c# – 为什么只有ForEach方法的列表全部内容,希望文章能够帮你解决c# – 为什么只有ForEach方法的列表所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1235977.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存