C# goto语句


一、C# goto语句

goto语句把控制交给由标记标识符命名的语句。

语法格式如下:

goto label;
......
label: ...在C#中,任何语句都可以被标记。语句标记后紧跟一个冒号,一个标记标识符。

常用的格式如下:

goto identifier;                // 标签
goto case constant-expression;  // switch-case标签
goto default;                   // switch语言中的默认标签?identifier:位于当前体中的标签、相同的词法范围或goto语言的封闭范围。
?case constant-expression:将控制传递给特定的switch-case标签。请阅读C# switch语句。
?default:将控制传递给switch语言中的默认标签。

二、提示

?goto语句还可以用于跳出深嵌套循环。

?goto语句只能在当前层内跳转。

?要避免使用goto语句。 

三、示例
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            // C# goto语句-www.baike369.com
            int x = 10;
            Console.WriteLine("x = {0}", x);
            if (x == 10)
            {
                x = 20;
                goto A;
            }
            x = x + 1;
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine(i);
            }
        A: Console.WriteLine("x = {0}", x);
           Console.ReadLine();
        }
    }
}

因为goto语句直接跳转到了A:处,所以for语句没有执行。

运行结果:
 
x = 10
x = 20

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM