在 C# 中,可以容納零個或多個元素的資料結構稱為_集合_。陣列是一種集合,它的大小與長度固定,而且所有元素都必須是相同的型別。你可以使用索引將元素指定給陣列,或從陣列中取出元素。C# 的陣列以零為起始索引,也就是說,第一個元素的索引一律是零:
// Declare array with explicit size (size is 2)
int[] twoInts = new int[2];
// Assign second element by index
twoInts[1] = 8;
// Retrieve the second element by index
twoInts[1] == 8; // => true
陣列也可以用簡寫語法來定義,同時建立陣列並設定它的值。由於編譯器現在能判斷陣列會有幾個元素,所以可以省略長度:
// Three equivalent ways to declare and initialize an array (size is 3)
int[] threeIntsV1 = new int[] { 4, 9, 7 };
int[] threeIntsV2 = new[] { 4, 9, 7 };
int[] threeIntsV3 = { 4, 9, 7 };
你可以呼叫陣列執行個體的方法或屬性來操作陣列,也可以使用Array類別中定義的靜態方法。
for迴圈for迴圈可以讓你重複執行某段程式碼,直到條件成立為止。
for (int i = 0; i < 5; i++)
{
System.Console.Write(i);
}
// => 01234
for迴圈由四個部分組成:
true,迴圈就會繼續執行。foreach迴圈陣列同時也是一種_集合_,這表示除了用索引存取值之外,你還可以用foreach迴圈走訪它的_所有_值:
char[] vowels = new [] { 'a', 'e', 'i', 'o', 'u' };
foreach (char vowel in vowels)
{
// Output the vowel
System.Console.Write(vowel);
}
// => aeiou
你是一位熱衷的賞鳥愛好者,會記錄過去七天有多少鳥飛到你的花園。
你有六個任務,全都和造訪你花園的鳥的數量有關。
為了方便比較,你總是會在身邊留一份上週的計數,分別是:0、2、5、3、7、8 和 4。請實作(static)BirdCount.LastWeek()方法,回傳上週的計數:
BirdCount.LastWeek();
// => [0, 2, 5, 3, 7, 8, 4]
請實作BirdCount.Today()方法,回傳今天有多少鳥造訪你的花園。鳥的計數是按日期排序的,第一個元素是最早那天的計數,最後一個元素則是今天的計數。
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
var birdCount = new BirdCount(birdsPerDay);
birdCount.Today();
// => 1
請實作BirdCount.IncrementTodaysCount()方法,將今天的計數加一:
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
var birdCount = new BirdCount(birdsPerDay);
birdCount.IncrementTodaysCount();
birdCount.Today();
// => 2
請實作BirdCount.HasDayWithoutBirds()方法,如果有某一天沒有任何鳥造訪花園,就回傳true;否則回傳false:
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
var birdCount = new BirdCount(birdsPerDay);
birdCount.HasDayWithoutBirds();
// => true
請實作BirdCount.CountForFirstDays()方法,回傳從這週開始以來造訪你花園的鳥數,但只計算從這週開始算起的指定天數。
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
var birdCount = new BirdCount(birdsPerDay);
birdCount.CountForFirstDays(4);
// => 14
有些日子比其他日子更忙碌。所謂忙碌的一天,是指有 5 隻或更多鳥造訪你的花園。
請實作BirdCount.BusyDays()方法,回傳忙碌的天數:
int[] birdsPerDay = { 2, 5, 0, 7, 4, 1 };
var birdCount = new BirdCount(birdsPerDay);
birdCount.BusyDays();
// => 2