Share via


不規則陣列 (C# 程式設計手冊)

更新:2007 年 11 月

不規則陣列是指這種陣列的元素也是陣列。不規則陣列的元素可以有不同維度及大小。不規則陣列有時稱為「陣列中的陣列」。下列範例會示範如何宣告、初始化和存取不規則陣列。

以下是一個一維陣列的宣告,其中有三個元素,而每個元素都是一維的整數陣列:

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

必須先初始化元素,才可以使用 jaggedArray。初始化元素的方法如下:

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

每個元素都是一維的整數陣列。第一個元素是具有五個整數的陣列,第二個是具有四個整數的陣列,而第三個是具有兩個整數的陣列。

您也可以使用初始設定式 (Initializer) 將值填入陣列元素,在此情況下,您就不需要陣列大小。例如:

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

您也可以在宣告時初始化陣列,如下所示:

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

您可使用下列縮寫格式:請注意,由於元素沒有預設的初始設定,您不能從元素初始設定中移除 new 運算子。

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

不規則陣列是指包含陣列的陣列,因此其元素為參考型別,而且會初始化為 null。

您可以存取個別陣列元素,如下列範例所示:

// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;

您也可以混合不規則陣列和多維陣列。以下是一個一維的不規則陣列,其中包含元素大小不同的二維陣列,其宣告及初始化如下:

int[][,] jaggedArray4 = new int[3][,] 
{
    new int[,] { {1,3}, {5,7} },
    new int[,] { {0,2}, {4,6}, {8,10} },
    new int[,] { {11,22}, {99,88}, {0,9} } 
};

如以下範例所示,您可以存取個別元素,其中顯示第一個陣列中元素 [1,0] 的值 (5 值):

System.Console.Write("{0}", jaggedArray4[0][1, 0]);

Length 方法會傳回包含在不規則陣列中的陣列數目。例如,假設您已經宣告先前的陣列,以下這行:

System.Console.WriteLine(jaggedArray4.Length);

會傳回 3 這個值。

範例

以下範例會建立一個陣列,它的元素本身也是陣列。每個陣列元素的大小都不同。

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

        // Initialize the elements:
        arr[0] = new int[5] { 1, 3, 5, 7, 9 };
        arr[1] = new int[4] { 2, 4, 6, 8 };

        // 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
*/

請參閱

概念

C# 程式設計手冊

參考

陣列 (C# 程式設計手冊)

一維陣列 (C# 程式設計手冊)

多維陣列 (C# 程式設計手冊)

Array