goto命令不起作用

时间:2014-10-31 15:11:14

标签: c# switch-statement goto

当我在没有goto命令的情况下执行代码时,它可以工作,但是当我添加:Start时,它会出现8错误。

以下是相关代码:

        :Start
        Console.Write("Do you want the yes or no?");
        string what = Console.ReadLine();
        switch (what)
        {
            case "yes":
                Console.WriteLine("You choose yes");
                break;
            case "no":
                Console.WriteLine("You choose no");
                break;
            default:
                Console.WriteLine("{0},is not a word",what);
                goto Start;
         }

3 个答案:

答案 0 :(得分:1)

正确的语法是Start:。但是,您应该在循环中设置它,而不是goto

bool invalid = true;
while (invalid)
{
    Console.Write("Do you want the yes or no?");
    string what = Console.ReadLine();
    switch (what)
    {
        case "yes":
            Console.WriteLine("You choose yes");
            invalid = false;
            break;
        case "no":
            Console.WriteLine("You choose no");
            invalid = false;
            break;
        default:
            Console.WriteLine("{0},is not a word",what);
     }
}

答案 1 :(得分:0)

尝试"开始:"而不是":开始" 像这样:

 Start:
            Console.Write("Do you want the yes or no?");
            string what = Console.ReadLine();
            switch (what)
            {
                case "yes":
                    Console.WriteLine("You choose yes");
                    break;
                case "no":
                    Console.WriteLine("You choose no");
                    break;
                default:
                    Console.WriteLine("{0},is not a word", what);
                    goto Start;
            }

http://msdn.microsoft.com/en-us/library/aa664740(v=vs.71).aspx

答案 2 :(得分:0)

标签的正确语法为Start:,而不是:Start

您可以重构代码以省略goto语句(better):

bool continue = true;
while (continue) {
   Console.Write("Do you want the yes or no?");
   string what = Console.ReadLine();
   switch (what)
   {
        case "yes":
            Console.WriteLine("You choose yes");
            continue = false;
            break;
        case "no":
            Console.WriteLine("You choose no");
            continue = false;
            break;
        default:
            Console.WriteLine("{0}, is not a word",what);
            break;
    }
}