Could someone please be kind enough to explain why there i开发者_JS百科s only a static/shared version of ForEach for arrays?
IE: ForEach<T>(T array[], System.Action(Of T) action[])
I assume this has something to do with the type inference requirements of implementing an instance method, but when you declare your array you provide type right?
One problem with arrays is that there's nowhere to document the instance methods which are available only on "vectors". A "vector" is a single-dimensional array with a base of 0 - so anything representable as T[]
in C# is a vector, but a T[,]
isn't, for example.
That means not every instance of Array
should have the method - and even if it did, how would you represent the T
? Each array type is separate, and there's no generic type in .NET which is a base class for all arrays. All we've got is Array
.
So, given that we have to introduce the type parameter somewhere in the type system, and given that we're also restricting it to "vector" types, a static method seems an appropriate workaround.
Note how this is not the case with List<T>
, where we already have the type parameter so can create a simple instance method.
It's also worth thinking about when using Array.ForEach
actually ends up with cleaner code than just using a foreach
loop. I would typically only use it when I'd already got a delegate to execute on each element. Otherwise the language construct feels cleaner, and it certainly more flexible in its ability to return or break out of the loop without an exception.
You provide T to tell what the array can contain in it. So since Array implements ienumerable, hence it gets ForEach extension method on it.
Is there any thing else your looking for?
Wondering if Erics post helps you http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx
精彩评论