C#的foreach
我要遍历哪个集合,然后 C# 会自动把里面的元素一个一个取出来给你用。你不需要管索引、不用写 i++,也不用担心数组越界。
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————
案例 1:遍历数组(最常用)
csharp
string[] fruits = { "苹果", "香蕉", "橙子" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
// 输出:苹果 香蕉 橙子
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————
案例 2:遍历数字列表并求和
csharp
List
int total = 0;
foreach (int score in scores)
{
total += score;
}
Console.WriteLine("总分:" + total); // 输出:总分:253
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————
案例 3:遍历字符串的每个字符
csharp
string name = "Hello";
foreach (char c in name)
{
Console.WriteLine(c);
}
// 输出:
// H
// e
// l
// l
// o

浙公网安备 33010602011771号