在 C# 中,能够容纳零个或多个元素的数据结构称为_集合_。数组是一种集合,它的大小/长度固定,并且所有元素都必须是同一类型。可以使用下标把元素赋给数组,也可以从数组中取出元素。C# 数组的下标从零开始,也就是说第一个元素的下标总是 0:
// 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
你是一位热心的观鸟爱好者,一直在记录过去 7 天里有多少只鸟来过你的花园。
你有 6 个任务,它们都和来你花园的鸟的数量有关。
为了便于比较,你总是把上周计数的副本放在手边,上周的计数是:0、2、5、3、7、8 和 4。实现(静态)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