數組
數組是一種資料結構,它包含若干相同類型的變數。數組是使用型別宣告的:
type[] arrayName;
下面的樣本建立一維、多維和交錯數組:
C# 複製代碼
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 };
}
}
數組概述
數組具有以下屬性:
數組可以是一維、多維或交錯的。
數值數組元素的預設值設定為零,而引用元素的預設值設定為 null。
交錯數組是數組的數組,因此,它的元素是參考型別,初始化為 null。
數組的索引從零開始:具有 n 個元素的數組的索引是從 0 到 n-1。
數組元素可以是任何類型,包括數群組類型。
數群組類型是從抽象基底類型 Array 派生的參考型別。由於此類型實現了 IEnumerable 和 IEnumerable,因此可以對 C# 中的所有數組使用 foreach 迭代。