數組是一種資料結構,它包含若干相同類型的變數。數組是使用型別宣告的:
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[] { 1, 3, 5, 7, 9 };
// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5, 6 };
// Declare a two dimensional array
int[,] multiDimensionalArray1 = new int[2, 3];
// Declare and set array element values
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
// 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] { 1, 2, 3, 4 };
}
}
在 C# 中,數組實際上是對象,而不只是像 C 和 C++ 中那樣的可定址連續記憶體地區。Array 是所有數群組類型的抽象基底類型。可以使用 Array 具有的屬性以及其他類成員。這種用法的一個樣本是使用 Length 屬性來擷取數組的長度。
數組可以具有多個維度。例如,下列聲明建立一個四行兩列的二維數組:
int[,] array = new int[4, 2];
下列聲明建立一個三維(4、2 和 3)數組:
int[, ,] array1 = new int[4, 2, 3];
初始化數組:
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
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[] { 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 運算子,因為不存在元素的預設初始化,交錯數組是數組的數組,因此其元素是參考型別並初始化為 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] { 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
*/