000: // Arrays\arrays.cs
001: using System;
002: class DeclareArraysSample
003: {
004: public static void Main()
005: {
006: // Single-dimensional array
007: int[] numbers = new int[5];
008:
009: // Multidimensional array
010: string[,] names = new string[5,4];
011:
012: // Array-of-arrays (jagged array)
013: byte[][] scores = new byte[5][];
014:
015: // Create the jagged array
016: for (int i = 0; i < scores.Length; i++)
017: {
018: scores[i] = new byte[i+3];
019: }
020:
021: // Print length of each row
022: for (int i = 0; i < scores.Length; i++)
023: {
024: Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
025: }
026: }
027: }
它的輸出是:
Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7
在C#中數組的初始化可以在建立時就初始化,和JAVA和C一樣,用的是{}.當然,很明顯,你的初始化值必須與你聲明的數群組類型一樣,比如你定義了一個int類型的,你就不能給它一個String,唉,JAVA看多了,在C#中,String應寫為string,要不然,又要出錯了.SUNWEN可能在後面的課程中出現這樣的錯誤,還望大家指正.呵呵!
下面的例子說明了數組的初始化:
int[] numbers = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[3] {"Matt", "Joanne", "Robert"};
你也可以省略數組的大小,如:
int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Matt", "Joanne", "Robert"};