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

陣列可以有一個以上的維度。 例如,下列宣告會建立四列兩行的二維陣列。

int[,] array = new int[4, 2];

下列宣告會建立 4、2 及 3 三個維度的陣列。

int[, ,] array1 = new int[4, 2, 3];

陣列初始化

您可以在宣告時初始化陣列,如下列範例所示。

// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
                                        { "five", "six" } };

// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                 { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                       { { 7, 8, 9 }, { 10, 11, 12 } } };

// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);

// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12

您也可以不指定陣序規範就初始化陣列。

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

如果您選擇不初始化就宣告陣列變數,您必須使用 new 運算子來將陣列指派至變數。 下列範例顯示 new 的用法。

int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };   // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

下列範例將值指派給特定的陣列元素。

array5[2, 1] = 25;

同樣,下列範例會取得特定陣列元素的值,並將其指派給變數 elementValue。

int elementValue = array5[2, 1];

下列程式碼範例會將陣列元素初始化為預設值 (除了不規則陣列之外)。

int[,] array6 = new int[10, 10];

請參閱

參考

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

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

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

概念

C# 程式設計手冊