宣告一個陣列

可以使用方括號([])初始化語法宣告陣列並使用預設值填充陣列。例如,建立一個包含 10 個整數的陣列:

int[] arr = new int[10];

C#中的指數是從零開始的。上面陣列的索引將是 0-9。例如:

int[] arr = new int[3] {7,9,4};
Console.WriteLine(arr[0]); //outputs 7
Console.WriteLine(arr[1]); //outputs 9

這意味著系統從 0 開始計算元素索引。此外,對陣列元素的訪問是在恆定時間內完成的。這意味著訪問陣列的第一個元素與訪問第二個元素,第三個元素等具有相同的成本(及時)。

你也可以在不例項化陣列的情況下宣告對陣列的裸引用。

int[] arr = null;   // OK, declares a null reference to an array.
int first = arr[0]; // Throws System.NullReferenceException because there is no actual array.

還可以使用集合初始化語法使用自定義值建立和初始化陣列:

int[] arr = new int[] { 24, 2, 13, 47, 45 };

宣告陣列變數時可以省略 new int[] 部分。這不是一個自包含的表示式,因此將其用作不同呼叫的一部分不起作用(為此,使用帶有 new 的版本):

int[] arr = { 24, 2, 13, 47, 45 };  // OK
int[] arr1;
arr1 = { 24, 2, 13, 47, 45 };       // Won't compile

隱式型別陣列

或者,結合 var 關鍵字,可以省略特定型別,以便推斷出陣列的型別:

// same as int[]
var arr = new [] { 1, 2, 3 };
// same as string[]
var arr = new [] { "one", "two", "three" };
// same as double[]
var arr = new [] { 1.0, 2.0, 3.0 };