I have an array defined:
我定义了一个数组:
int [,] ary;
// ...
int nArea = ary.Length; // x*y or total area
This is all well and good, but I need to know how wide this array is in the x
and y
dimensions individually. Namely, ary.Length
might return 12 - but does that mean the array is 4 high and 3 wide, or 6 high and 2 wide?
这很好,但是我需要知道这个数组在x和y维上的宽度。也就是说,必要。长度可能返回12——但这是否意味着数组是4高3宽,还是6高2宽?
How can I retrieve this information?
我如何检索这些信息?
5 个解决方案
#1
156
You use Array.GetLength with the index of the dimension you wish to retrieve.
你使用数组。GetLength与您希望检索的维度的索引。
#2
69
Use GetLength(), rather than Length.
使用GetLength()而不是Length。
int rowsOrHeight = ary.GetLength(0);
int colsOrWidth = ary.GetLength(1);
#3
28
// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10
#4
20
ary.GetLength(0)
ary.GetLength(1)
for 2 dimensional array
2维数组
#5
15
Some of the other posts are confused about which dimension is which. Here's an NUNIT test that shows how 2D arrays work in C#
其他一些帖子对哪个维度是哪个维度感到困惑。这里有一个NUNIT测试,展示了2D数组在c#中的工作方式
[Test]
public void ArraysAreRowMajor()
{
var myArray = new int[2,3]
{
{1, 2, 3},
{4, 5, 6}
};
int rows = myArray.GetLength(0);
int columns = myArray.GetLength(1);
Assert.AreEqual(2,rows);
Assert.AreEqual(3,columns);
Assert.AreEqual(1,myArray[0,0]);
Assert.AreEqual(2,myArray[0,1]);
Assert.AreEqual(3,myArray[0,2]);
Assert.AreEqual(4,myArray[1,0]);
Assert.AreEqual(5,myArray[1,1]);
Assert.AreEqual(6,myArray[1,2]);
}
#1
156
You use Array.GetLength with the index of the dimension you wish to retrieve.
你使用数组。GetLength与您希望检索的维度的索引。
#2
69
Use GetLength(), rather than Length.
使用GetLength()而不是Length。
int rowsOrHeight = ary.GetLength(0);
int colsOrWidth = ary.GetLength(1);
#3
28
// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10
#4
20
ary.GetLength(0)
ary.GetLength(1)
for 2 dimensional array
2维数组
#5
15
Some of the other posts are confused about which dimension is which. Here's an NUNIT test that shows how 2D arrays work in C#
其他一些帖子对哪个维度是哪个维度感到困惑。这里有一个NUNIT测试,展示了2D数组在c#中的工作方式
[Test]
public void ArraysAreRowMajor()
{
var myArray = new int[2,3]
{
{1, 2, 3},
{4, 5, 6}
};
int rows = myArray.GetLength(0);
int columns = myArray.GetLength(1);
Assert.AreEqual(2,rows);
Assert.AreEqual(3,columns);
Assert.AreEqual(1,myArray[0,0]);
Assert.AreEqual(2,myArray[0,1]);
Assert.AreEqual(3,myArray[0,2]);
Assert.AreEqual(4,myArray[1,0]);
Assert.AreEqual(5,myArray[1,1]);
Assert.AreEqual(6,myArray[1,2]);
}