iterating through 2-d array in VB.Net
I was amazed (and horrified) that the following code works in Vb.Net
Dim test2DArr As String(,) = {{"A", "B"}, {"C", "D"}}
For Each s As String In test2DArr
MsgBox(s)
Next
When run, four message boxes pop up showing "A", "B", "C", and then "D".
In other words, it has exactly the same behavior as:
Dim test1DArr As String() = {"A", "B", "C", "D"}
For Each s As String In test1DArr
MsgBox(s)
Next
Can someone explain this "Feature" ? I need to impose some structure here that is apparently not supported. The first code example above should be:
Dim test2DArr As String(,) = {{"A", "B"}, {"C", "D"}}
For Each arr As String(,) In test2DArr
MsgBox(arr(0) & ", " & arr(1))
Next
and should produc开发者_StackOverflowe two message boxes: "A, B" and "C, D", but the compiler insists that iterating through a 2-d array yields a sequence of strings, not a sequence of arrays of strings.
Am I doing something wrong or is .Net's implementation of 2-D arrays really that flimsy?
is .Net's implementation of 2-D arrays really that flimsy?
Yes. Multi-dimensional arrays were never really supported in .NET. I’m not sure why they exist at all (as opposed to arrays-of-arrays, i.e. jagged arrays: String()()). In any case, all the support is tailored to the special case of one-dimensional arrays. The framework type for arrays is always the same, regardless of dimensionality, and the interface implementation (in this case of IEnumerable(Of T)) is tailored to this common use case.
This means that the type of the array is always an “array of strings”, and thus it always implements the interface IEnumerable(Of String). This explains why your second code cannot work: in order for it to work, the type of the array would have to be different.
加载中,请稍侯......
精彩评论