c#中的goto用法

来源:百度知道 编辑:UC知道 时间:2024/05/16 20:15:40
start:
int myInteger = 5;
goto addVal;
writeResult:
Console.WriteLine("myInteger = {0}", myInteger);
goto start;
addVal:
myInteger += 10;
goto writeResult
什么意思

一般GOTO建议只用在多重循环的跳出,其它情况尽量不用,因为可读性不高。
start://标号start
int myInteger = 5;
goto addVal;//1.跳到标号addVal
writeResult://3.从第二步跳到这里,执行打印
Console.WriteLine("myInteger = {0}", myInteger);
goto start;//4.再跳到标号start,重新给myInteger赋值
addVal:
myInteger += 10;//2.myInteger自增10,变成15
goto writeResult//跳到标号writeResult
注意我写的1,2,3,4,那是执行步骤,因为这代码是个死循环。

goto 语句将程序控制直接传递给标记语句。

goto 的一个通常用法是将控制传递给特定的 switch-case 标签或 switch 语句中的默认标签。
goto 语句还用于跳出深嵌套循环。

示例
下面的示例演示了 goto 在 switch 语句中的使用。

复制代码
// statements_goto_switch.cs
using System;
class SwitchTest
{
static void Main()
{
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();