Why does the generic Dictionary in .NET not provide a ForEach() method?

廉价感情. 提交于 2021-01-28 05:22:02

问题


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.)

Thanks in advance.


回答1:


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(Foo foo in foos){ statement involving foo; }

into this code:

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. (...)



来源:https://stackoverflow.com/questions/46229829/why-does-the-generic-dictionary-in-net-not-provide-a-foreach-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!