gpt4 book ai didi

c# - 为什么 ForEach 方法只适用于列表

转载 作者:太空狗 更新时间:2023-10-29 17:28:38 25 4
gpt4 key购买 nike

据我所知,ForEach 方法仅适用于 List class .

这是为什么呢?我看不出有什么理由让 ForEach 对任何实现 IEnumerable/IEnumerator 接口(interface)的类不可用,这是一个非常有用的方法,如果您需要执行一个小操作(1 行比 1 行 + 2 个样板 foreach 语法更具可读性...)。

更新:我会澄清我的问题。在序列中包含 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 方法只适用于列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2178167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com