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