代码改变世界

C# 一维 多维 交叉数组

2011-10-14 10:19  Eric.Hu  阅读(879)  评论(1编辑  收藏  举报

数组是一种数据结构,它包含若干相同类型的变量。数组是使用类型声明的:

type[] arrayName;

下面的示例创建一维、多维和交错数组:

 

class TestArraysClass 

{
    static void Main()
    {
        // Declare a single-dimensional array 
        int[] array1 = new int[5];

        // Declare and set array element values
        int[] array2 = new int[] { 13579 };

        // Alternative syntax
        int[] array3 = { 123456 };

        // Declare a two dimensional array
        int[,] multiDimensionalArray1 = new int[23];

        // Declare and set array element values
        int[,] multiDimensionalArray2 = { { 123 }, { 456 } };

        // Declare a jagged array
        int[][] jaggedArray = new int[6][];

        // Set the values of the first array in the jagged array structure
        jaggedArray[0] = new int[4] { 1234 };
    }
}

 在 C# 中,数组实际上是对象,而不只是像 C 和 C++ 中那样的可寻址连续内存区域。Array 是所有数组类型的抽象基类型。可以使用 Array 具有的属性以及其他类成员。这种用法的一个示例是使用 Length 属性来获取数组的长度。

 

数组可以具有多个维度。例如,下列声明创建一个四行两列的二维数组:

 int[,] array = new int[42];

下列声明创建一个三维(4、2 和 3)数组: 

 int[, ,] array1 = new int[423];

初始化数组:

int[,] array2D = new int[,] { { 12 }, { 34 }, { 56 }, { 78 } };

int[, ,] array3D =  [,,] { { {  } }, { {  newint123456 } } };


交错数组是元素为数组的数组。交错数组元素的维度和大小可以不同。交错数组有时称为“数组的数组”。以下示例说明如何声明、初始化和访问交错数组。

下面声明一个由三个元素组成的一维数组,其中每个元素都是一个一维整数数组: 

int[][] jaggedArray = new int[3][];

初始化数组

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4]; 

jaggedArray[2] = new int[2];

 或

jaggedArray[0] = new int[] { 13579 };
jaggedArray[1] = new int[] { 0246 };

jaggedArray[2] = new int[] { 1122 }; 

int[][] jaggedArray2 = new int[][] 
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}

};

 不能从元素初始化中省略 new 运算符,因为不存在元素的默认初始化,交错数组是数组的数组,因此其元素是引用类型并初始化为 null。 

交错数组示例 :

class ArrayTest
{
    static void Main()
    {
        // Declare the array of two elements:
        int[][] arr = new int[2][];

        // Initialize the elements:
        arr[0] = new int[5] { 13579 };
        arr[1] = new int[4] { 2468 };

        // Display the array elements:
        for (int i = 0; i < arr.Length; i++)
        {
            System.Console.Write("Element({0}): ", i);

            for (int j = 0; j < arr[i].Length; j++)
            {
                System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");
            }
            System.Console.WriteLine();            
        }
        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    Element(0): 1 3 5 7 9
    Element(1): 2 4 6 8

*/