foreach循環用於列舉出集合中所有的元素,使用foreach可以迭代數組或者一個集合對象。
<組成>
<循環過程>
每一次循環時,從集合中取出一個新的元素值,放到只讀變量中去,如果括號中的整個表達式返回值爲true,foreach塊中的語句就能執行。一旦集合中的元素都應經被訪問到,整個表達式的值爲false,控制流程就轉入到foreach塊後面的執行語句。
<遍歷數組>
class Program
{
static void Main(string[] args)
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in array)
{
Console.WriteLine(i);
}
}
}
它實現了對數組元素的遍歷,遍歷之前需要指定元素的類型
//結果
1
2
3
4
5
6
7
8
9
<遍歷字符串>
class Program
{
static void Main(string[] args)
{
string test = "Hello,world!";
foreach (char i in test)
{
Console.WriteLine(i);
}
}
}
//結果
H
e
l
l
o
,
w
o
r
l
d
!
將i的類型char換成int
//結果
72
101
108
108
111
44
119
111
114
108
100
33
輸出的結果是字符所對應的ASCII碼值,說明這裏進行了數據類型的隱式轉換
<註釋>
- 變量名用來存放該集合中的每個元素
- ArrayList或List是一個類,它可以讓foreach去遍歷
<舉例>
class Program
{
static void Main(string[] args)
{
int count;
Console.WriteLine("輸入要登記的學生數");
count = int.Parse(Console.ReadLine());
string[] names = new string[count];//聲明一個存放姓名的字符串數組,其長度等於提供的學生人數
for (int i = 0; i < names.Length; i++)//接受姓名
{
Console.WriteLine("請輸入第{0}個學生的姓名", i + 1);
names[i] = Console.ReadLine();
}
Console.WriteLine("已登記的學生如下");
foreach (string name in names)//顯示姓名
{
Console.WriteLine("{0}", name);
}
Console.ReadKey();
}
}
<注意>:
- foreach循環是隻讀的,不能遍歷修改數據
- foreach循環是隻進的,並且是一條一條循環的