为什么.NET中的通用Dictionary不提供ForEach()方法? [英] Why does the generic Dictionary in .NET not provide a ForEach() method?

查看:60
本文介绍了为什么.NET中的通用Dictionary不提供ForEach()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过几个小时的研究(在MSDN网站等上),我没有找出为什么通用Dictionary<TKey, TValue>不提供像List<T>那样的ForEach()方法的原因.有人可以给我一个解释吗? (我知道将其实现为扩展方法并不难,可以在此处查看一个很好的示例,我只是想知道是否可能有一个特定的原因导致.NET库最初没有提供它.)

After a couple hours of research (on MSDN websites and so on) I didn't manage to find out why the generic Dictionary<TKey, TValue> does not provide a ForEach() method like List<T> does. Could someone please give me an explanation? (I know that it's not hard to implement it as an extension method, a great example can be seen here, I just was wondering whether there might be a particular reason why it's not provided by the .NET libraries in the first place.)

谢谢.

推荐答案

因为为什么List<T>首先拥有它是有疑问的.无需到处重复相同的错误.埃里克·利珀特(Eric Lippert)在其博客文章中给出了两个原因:

Because it's questionable why List<T> has it in the first place. No need to repeat the same mistake everywhere. Eric Lippert gives two reason as to why in his blog post :

第一个原因是这样做违反了所有其他序列运算符所基于的功能编程原理.显然,调用此方法的唯一目的是引起副作用. (...)

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. Doing this lets you rewrite this perfectly clear code:

foreach(foos中的foo foo){涉及foo的语句; }

foreach(Foo foo in foos){ statement involving foo; }

输入此代码:

foos.ForEach((Foo foo)=> {涉及foo;的语句);

foos.ForEach((Foo foo)=>{ statement involving foo; });

使用几乎完全相同的字符,但顺序略有不同.但是,第二个版本更难理解,更难调试,并且引入了闭包语义,从而有可能以微妙的方式更改对象的生存期. (...)

which uses almost exactly the same characters in slightly different order. And yet the second version is harder to understand, harder to debug, and introduces closure semantics, thereby potentially changing object lifetimes in subtle ways. (...)

这篇关于为什么.NET中的通用Dictionary不提供ForEach()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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