using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 多维数组的定义与使用 { class Program { static void Main(string[] args) { Console.WriteLine("Now, we are traversing the multidimention array..."); //[多维数组] //方式1, 只声明,不初始化,定义一个矩形数组 double[,] Array1 = new double[4, 5]; //方式2,既声明,又初始化 int[,] Array2 = new int[,] {{1,2,3,4,5}, {2,4,6,8,10}, {3,6,9,12,15}, {4,8,16,32,36}}; //遍历多维数组 //foreach(int element in Array2) //{ // Console.Write("{0} ", element); //} //Console.WriteLine(); int lastRow = Array2.GetUpperBound(0); for (int i = 0; i <= lastRow; i++) { //Array2.GetUpperBound(1)方法的参数1是指第二维(列) int lastColumn = Array2.GetUpperBound(1); for (int j = 0; j <= lastColumn; j++) { Console.Write("{0} ",Array2[i, j]); } Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("Now, we are traversing the jagged array..."); //[数组的数组] //定义一个变长数组,要在数组的声明中指定多个方括号对,但是下面两种方式是错误的 //int [][] jaggedIntArray1 = new int[3][4]; //int [][] jaggedIntArray2 = {{1,2,3},{3},{3,4}}; //只能使用下面两种方式: //1,初始化包含其它数组的数组,然后依次初始化子数组 int[][] jaggedIntArray1 = new int[2][]; jaggedIntArray1[0] = new int[3]; jaggedIntArray1[1] = new int[4]; //2,改进为在一条语句中初始化,在这里用到了声明一维数组时,在一条语句中既声明,又初始化,又赋值的方法 //int[] arr1 = new int[] {1,2,3,4,5}; int[][] jaggedIntArray2 = { new int[] { 1, 2, 3 }, new int[] { 1 }, new int[] { 2, 3 } }; //遍历变长数组,因为数组又包含int[]元素而不是int元素,必须循环每个子数组和数组本身 //所以用一个foreach的嵌套 //foreach (int[] elementsOfInt in jaggedIntArray2) //{ // foreach (int elements in elementsOfInt) // { // Console.Write("{0} ", elements); // } //} //Console.WriteLine(); //数组的数组只有一维,只不过各元素是数组罢了 int row = jaggedIntArray2.GetUpperBound(0); //指定在母数组中循环各元素(这里的元素是子数组) for(int k= 0; k<=row;k++) { //注意,使用Array.Length属性与使用Array.GetupperBound()来获取数组中数组元素的个数是有区别的 //因为使用Array.Length属性,是获取所有维的数组的长度,而使用Array.GetupperBound(i),是获取指定第i维中数组元素的个数 //在对多维数组进行操作时,是有区别的,一般用Array.GetupperBound(i),或者Array.GetLength(i) //GetUpperBound returns the highest index of that array instead of the number of values in that array. //GetLength() returns the total number of elements and getUpperBound returns the highest index number (getLength - 1) in most cases. //GetUpperBound() can also be used on arrays of 2 or more dimensions to get the upper index of a dimension. //GetLength returns the number of items in the specified dimension. //GetUpperBound returns the index of the last item in the specified dimension. //For a one dimensional zero based array (which is the usual) that holds 10 items, GetLength(0) returns 10, while GetUpperBound(0) returns 9. for (int m = 0; m <= jaggedIntArray2[k].GetUpperBound(0); m++) { Console.Write("{0} ", jaggedIntArray2[k][m]); } Console.WriteLine(); } Console.ReadKey(); } } }