问题
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