首页 > 解决方案 > goto - 不在范围内(C#)

问题描述

我对代码很陌生。谁能以简单的方式解释为什么我不能像这样使用 goto 语句来使代码重新开始?或者,如何以正确的方式做到这一点?还有,为什么我会收到关于使用“静态”的错误消息。** "goto statmenet 范围内没有这样的标签 "Start"" "修饰符 static 对此项无效"

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;
                    } }
            }


        }
    }
}

标签: c#goto

解决方案


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

其次:goto在单一方法内有效;您可以跳过单个堆栈帧 - 您不能在堆栈帧之间跳转。

第三:你应该使用的次数goto......嗯,它不是完全为零,但它渐近接近零


推荐阅读