C# goto

在 C# 中,goto 语句将控制转移到程序中的其他部分。例如,

goto label;
... 
...
label:
  ...
  ...

这里,label 是一个标识符。当遇到 goto label; 时,程序的控制会转移到 label:。然后,执行 label: 下方的代码。

Working of goto in C#
goto 在 C# 中的工作方式

示例:C# goto

using System;

namespace CSharpGoto {

  class Program {
    public static void Main(string[] args) {
      
// label repeat:
Console.WriteLine("Enter a number less than 10"); int num = Convert.ToInt32(Console.ReadLine()); if(num >= 10) {
// transfers control to repeat goto repeat;
} Console.WriteLine(num + " is less than 10"); Console.ReadLine(); } } }

输出

Enter a number less than 10
99
Enter a number less than 10
9
9 is less than 10

在上面的程序中,我们在 if 语句中使用了 goto 语句。

如果输入的数字不小于 10goto repeat: 会将代码的控制转移到 repeat:。然后,执行 repeat: 下方的代码。

除非输入的数字小于 10,否则代码的控制将转移到 repeat: 标签。


goto 与 switch 语句结合使用(C#)

在 C# 中,我们可以使用 goto 语句和 switch 语句将程序的控制转移到特定的 case。例如,

using System;

namespace CSharpGoto {

  class Program {

    public static void Main(string[] args) {

      Console.Write("Choose your coffee? milk or black: ");
      string coffeeType = Console.ReadLine();

      switch (coffeeType) {
        case "milk":
          Console.WriteLine("Can I have a milk coffee?");
          break;

        case "black":
          Console.WriteLine("Can I have a black coffee?");
// transfer code to case "milk" goto case "milk";
default: Console.WriteLine("Not available."); break; } Console.ReadLine(); } } }

输出

Can I have a black coffee?
Can I have a milk coffee?

在上面的程序中,我们使用了带 switch 语句的 goto 语句。

我们将 coffeeType 输入为 "black"。现在,将执行 case "black"

在 case 中,我们使用了 goto case "milk";,它会将程序的控制转移到 case "milk"

因此,两个 case 都被执行了。


goto 与 for 循环结合使用

在 C# 中,我们可以使用 goto 来跳出 for 循环。例如,

using System;

namespace CSharpGoto {

  class Program {

    static void Main() {
    for(int i = 0; i <= 10; i++) {

      if(i == 5) {
// transfers control to End label goto End;
} Console.WriteLine(i); }
// End label End:
Console.WriteLine("Loop End"); Console.ReadLine(); } } }

输出

0
1
2
3
4
Loop End

在上面的程序中,我们创建了一个 for 循环。它从 0 迭代到 100

i 的值等于 5 时,goto 语句将代码的控制转移到 End 标签。因此,程序跳出了 for 循环。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战