多维数组不实现IEnumerable&LT; T&GT ;,还是他们? [英] Multidimensional arrays do not implement IEnumerable<T>, or do they?
问题描述
有关,我还是不明白的原因(<一个href=\"http://stackoverflow.com/questions/275073/why-does-c-multidimensional-arrays-not-implement-ienumerablet\">see这太问题)在CLR多维数组不执行的IEnumerable&LT; T&GT;
。所以下面的不能编译:
VAR M =新的INT [2,2] {{1,2},{3,4}};
变种Q =从电子以m选择电子;
那么怎么来这的在VB.NET中工作得很好
的Sub Main()
昏暗的M(,)作为整数= {{1,2},{3,4}}
昏暗的Q =从电子在并购选择e 每个I期q
Console.WriteLine(ⅰ)
下一个
结束小组
更新:
以下code工作,因为C#编译器替换的foreach
与为
循环都要经过各尺寸。
的foreach(米变种E)
Console.WriteLine(E);
变为
INT [,] numArray3 =新INT [,] {{2,2},{3,3}};
INT UPPERBOUND = numArray3.GetUpperBound(0);
INT num4 = numArray3.GetUpperBound(1);
的for(int i = numArray3.GetLowerBound(0); I&LT; = UPPERBOUND;我++)
{
为(中间体J = numArray3.GetLowerBound(1); J&下; = num4; J ++)
{
INT NUM = numArray3 [I,J]。
Console.WriteLine(NUM);
}
}
查询在VB.Net的作品,因为它被改造成
的IEnumerable&LT;对象&gt; Q = m.Cast&LT;对象&gt;()选择&LT;对象,对象&gt;(O =≠0);
这工作,因为你可以叫演员lt;有关
的IEnumerable
,其中(); TResult&GT > [*,*]
工具。
LINQ查询并不在C#中工作,因为不同的方法C#和VB.Net设计者们。 VB.Net需要更多手握方法,并修复自己的错误,并皈依的IEnumerable
到的IEnumerable&LT;对象&gt;
因此它可以使用
在C#中,您可以通过使用模拟这种
VAR•从E在m.Cast&LT =;对象&gt;()选择e;
For the reasons that I still do not understand (see this SO question) multidimensional arrays in CLR do not implement IEnumerable<T>
. So the following does not compile:
var m = new int[2,2] {{1, 2}, {3, 4}};
var q = from e in m select e;
Then how come that this works just fine in VB.NET?
Sub Main()
Dim m(,) As Integer = {{1, 2}, {3, 4}}
Dim q = From e In m Select e
For Each i In q
Console.WriteLine(i)
Next
End Sub
Update:
The following code works because the C# compiler replaces the foreach
with for
loops to go through each dimension.
foreach(var e in m)
Console.WriteLine(e);
becomes
int[,] numArray3 = new int[,] { { 2, 2 }, { 3, 3 } };
int upperBound = numArray3.GetUpperBound(0);
int num4 = numArray3.GetUpperBound(1);
for (int i = numArray3.GetLowerBound(0); i <= upperBound; i++)
{
for (int j = numArray3.GetLowerBound(1); j <= num4; j++)
{
int num = numArray3[i, j];
Console.WriteLine(num);
}
}
The query works in VB.Net because it gets transformed into
IEnumerable<object> q = m.Cast<object>().Select<object, object>(o => o);
This works because you can call Cast<TResult>
() on IEnumerable
, which [*,*]
implements.
The LINQ query doesn't work in C# because of the different approach the C# and VB.Net designers took. VB.Net takes a more hand holding approach and fixes your mistake and converts IEnumerable
to IEnumerable<object>
so it can be used.
In C#, you can simulate this by using
var q = from e in m.Cast<object>() select e;
这篇关于多维数组不实现IEnumerable&LT; T&GT ;,还是他们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!