hello

C#规则数组和不规则数组

见下列代码:

        static void Main(string[] args)
        {
            int[,] a = new int[,] { { 0, 1, 2, 3 }, { 2, 3, 4, 5 }, { 3, 4, 5, 6 } };
            Console.WriteLine("规则数组:");
            Console.WriteLine(a.Length);
            Console.WriteLine(a.GetLength(0));
            Console.WriteLine(a.GetLength(1));

            int[][] b = new int[3][];
            b[0] = new int[4];
            b[1] = new int[5];
            b[2] = new int[4];
            //b[3] = new int[5];
            Console.WriteLine("不规则数组:");
            Console.WriteLine(b.Length);
            Console.WriteLine(b.GetLength(0));
            //调用将会出错: Console.WriteLine(b.GetLength(1));
            Console.WriteLine(b[0].Length);
            Console.Read();
        }

输出结果为:
规则数组:

12

3

4

不规则数组

3

3

4

第一个规则数组很好理解,但是第二个不规则数组,为什么b.GetLength(0)和b[0].Length不一样。

调试监视变量结果如下图:

通过上图可以发现b.GetLength(0)其实取的是b数组里面共有几个一维数组,这里我们定义 int[][] b = new int[3][];所以结果为3

而b[0].Length则是取的b数组里面的第一个一维数组的长度,这里我们定义了  b[0] = new int[4];所以结果为4

在这里我们可以给b里面的第一个一维数组赋值:b[0][0] = 5;或者   b[0] = new int[4]{1,2,3,4};

这样b[0]数组里面就有值了。

 

 

 

 

posted @ 2012-12-13 16:31  B追风少年  阅读(3064)  评论(0编辑  收藏  举报

hello too