一維數組
可按下面的示例所示聲明五個整數的一維數組。
int[] array = new int[5];
此數組包含從 array[0] 到 array[4] 的元素。 new 運算符用于創建數組并將數組元素初始化為它們的默認值。在此例中,所有數組元素都初始化為零。
可以用相同的方式聲明存儲字符串元素的數組。例如:
string[] stringArray = new string[6];
數組初始化
可以在聲明數組時將其初始化,在這種情況下不需要級別說明符,因為級別說明符已經由初始化列表中的元素數提供。例如:
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
可以用相同的方式初始化字符串數組。下面聲明一個字符串數組,其中每個數組元素用每天的名稱初始化:
string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
如果在聲明數組時將其初始化,則可以使用下列快捷方式:
int[] array2 = { 1, 3, 5, 7, 9 };string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
可以聲明一個數組變量但不將其初始化,但在將數組分配給此變量時必須使用 new 運算符。例如:
int[] array3;array3 = new int[] { 1, 3, 5, 7, 9 }; // OK//array3 = {1, 3, 5, 7, 9}; // Error
值類型數組和引用類型數組
請看下列數組聲明:
SomeType[] array4 = new SomeType[10];
該語句的結果取決于 SomeType 是值類型還是引用類型。如果為值類型,則語句將創建一個有 10 個元素的數組,每個元素都有 SomeType 類型。如果 SomeType 是引用類型,則該語句將創建一個由 10 個元素組成的數組,其中每個元素都初始化為空引用。
多維數組
數組可以具有多個維度。例如,下列聲明創建一個四行兩列的二維數組。
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]);// Getting the total count of elements or the length of a given dimension.var allLength = array3D.Length;var total = 1;for (int i = 0; i < array3D.Rank; i++) { total *= array3D.GetLength(i);}System.Console.WriteLine("{0} equals {1}", allLength, total);
輸出:
12347three81212 equals 12
也可以初始化數組但不指定級別。
int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
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];
新聞熱點
疑難解答