在 C# 中,我们使用 break
语句来终止循环。
众所周知,循环会迭代执行一段代码,直到测试表达式为 false。然而,有时我们需要在不检查测试表达式的情况下立即终止循环。
在这种情况下,会使用 break
语句。break
语句的语法是:
break;
在学习 break
之前,请确保您已学习:
示例:C# for 循环中的 break 语句
using System;
namespace CSharpBreak {
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 4; ++i) {
// terminates the loop
if (i == 3) {
break;
}
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
输出
1 2
在上面的程序中,我们的 for
循环从 i = 1
运行到 4 次。但是,当 i
等于 3 时,遇到了 break
语句。
if (i == 3) {
break;
}
现在,循环突然终止。因此,我们只能得到 1 和 2 的输出。
注意:break
语句与 if..else 等决策语句一起使用。
示例:C# while 循环中的 break 语句
using System;
namespace WhileBreak {
class Program {
static void Main(string[] args) {
int i = 1;
while (i <= 5) {
Console.WriteLine(i);
i++;
if (i == 4) {
// terminates the loop
break;
}
}
Console.ReadLine();
}
}
}
输出
1 2 3
在上面的示例中,我们创建了一个 while
循环,该循环应该从 i = 1
运行到 5。
但是,当 i
等于 4 时,遇到了 break
语句。
if (i == 4) {
break;
}
现在,while 循环终止了。
C# 中 break 语句的工作原理

break 语句与嵌套循环
我们也可以将 break
语句与嵌套循环一起使用。例如:
using System;
namespace NestedBreak {
class Program {
static void Main(string[] args) {
int sum = 0;
for(int i = 1; i <= 3; i++) { //outer loop
// inner loop
for(int j = 1; j <= 3; j++) {
if (i == 2) {
break;
}
Console.WriteLine("i = " + i + " j = " +j);
}
}
Console.ReadLine();
}
}
}
输出
i = 1 j = 1 i = 1 j = 2 i = 1 j = 3 i = 3 j = 1 i = 3 j = 2 i = 3 j = 3
在上面的示例中,我们在内部 for
循环中使用了 break 语句。这里,当 i == 2
时,将执行 break 语句。
因此,i = 2
的值永远不会被打印。
注意:break 语句仅终止内部 for
循环。这是因为我们在内部循环中使用了 break
语句。
如果您想了解嵌套循环的工作原理,请访问 C# 嵌套循环。
break 语句与 foreach 循环
我们也可以将 break
语句与 foreach 循环一起使用。例如:
using System;
namespace ForEachBreak {
class Program {
static void Main(string[] args) {
int[] num = { 1, 2, 3, 4, 5 };
// use of for each loop
foreach(int number in num) {
// terminates the loop
if(number==3) {
break;
}
Console.WriteLine(number);
}
}
}
}
输出
1 2
在上面的示例中,我们创建了一个包含值 1、2、3、4、5 的数组。这里,我们使用 foreach
循环打印数组的每个元素。
但是,循环仅打印 1 和 2。这是因为当数字等于 3 时,执行了 break 语句。
if (number == 3) {
break;
}
这会立即终止 foreach 循环。
break 语句与 Switch 语句
我们也可以在 switch case 语句中使用 break
语句。例如:
using System;
namespace ConsoleApp1 {
class Program {
static void Main(string[] args) {
char ch='e';
switch (ch) {
case 'a':
Console.WriteLine("Vowel");
break;
case 'e':
Console.WriteLine("Vowel");
break;
case 'i':
Console.WriteLine("Vowel");
break;
case 'o':
Console.WriteLine("Vowel");
break;
case 'u':
Console.WriteLine("Vowel");
break;
default:
Console.WriteLine("Not a vowel");
}
}
}
}
输出
Vowel
在这里,我们在每个 case 中都使用了 break
语句。当找到匹配的 case 时,它有助于我们终止 switch 语句。
要了解更多信息,请访问 C# switch 语句。