gpt4 book ai didi

c# - goto - 不在范围内 (C#)

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:18 25 4
gpt4 key购买 nike

我对代码很陌生。谁能以简单的方式解释为什么我不能像这样使用 goto 语句来使代码重新开始?或者,这怎么可能以正确的方式完成?而且,为什么我收到有关使用“静态”的错误消息。**“在 goto statmenet 的范围内没有这样的标签“开始””“修饰符 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;
} }
}


}
}
}

最佳答案

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

其次:goto 仅在单个方法中有效;您可以在单个堆栈帧周围跳转 - 您不能在 堆栈帧之间跳转。

第三:您应该使用 goto 的次数......好吧,它不是相当零,但它 < em>渐近趋近于零。

关于c# - goto - 不在范围内 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50783274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com