How do you get the width and height of a multi-dimensional array?

前端 未结 6 2017
清酒与你
清酒与你 2020-11-27 13:48

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

6条回答
  •  清酒与你
    2020-11-27 14:33

    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#

    [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]);
    }
    

提交回复
热议问题