转到 - 不在范围内(C#)

Kev*_*MVP 1 c# goto

我对代码很新.任何人都可以用一种简单的方式解释为什么我不能像这样使用goto语句,让代码重新开始?或者,如何以正确的方式完成这项工作?而且,为什么我收到关于使用"静态"的错误消息.**"没有这样的标签"在goto statmenet范围内"开始""修饰符静态对此项目无效"

using System;


namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            Start:

            Random numberGenerator = new Random();

            int num1 = numberGenerator.Next(1,11);
            int num2 = numberGenerator.Next(1, 4);


            Console.WriteLine("What is " + num1 + " times " + num2 + "?");


            int svar = Convert.ToInt32(Console.ReadLine());

            if (svar == num1 * num2)
            {
                Console.WriteLine("well done!");
            }
            else
            {
                int responseIndex = numberGenerator.Next(1, 4);

                switch (responseIndex)
                {
                    case 1:
                        Console.WriteLine("Wrong, try again? [Y or N]");
                        AskUser();
                        break;
                    case 2:
                        Console.WriteLine("The answer was incorrect");
                        AskUser();
                        break;
                    default:
                        Console.WriteLine("You can do better than that");
                        AskUser();
                        break;
                }



                 static void AskUser() {
                    string jaellernei = Console.ReadLine().ToUpper();
                    if (jaellernei == "Y")
                    {
                     goto Start;
                    } else
                    {
                        return;
                    } }
            }


        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 8

首先,您的AskUser方法被错误地嵌套在另一个方法中 - 将其移出.

其次:goto在一种方法中有效; 你可以跳转到一个堆栈帧 - 你不能堆栈帧之间跳转.

第三:你应该使用的次数goto......好吧,它不是零,但它渐近逼近零.

  • 它不一定是嵌套错误的.C#现在支持本地函数,它们只需要用`static`关键字声明,即使它们是`static`方法的一部分. (2认同)