c# - 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;
} }
}
}
}
}
解决方案
首先,您的AskUser
方法错误地嵌套在另一个方法中 - 将其移出。
其次:goto
仅在单一方法内有效;您可以跳过单个堆栈帧 - 您不能在堆栈帧之间跳转。
第三:你应该使用的次数goto
......嗯,它不是完全为零,但它渐近接近零。
推荐阅读
- dji-sdk - Gimbal Rotation - 在旋转完成之前触发 withCompletion 方法
- python - 递归查找列表列表中的最小值
- swift - 在 ForEach 迭代中将数据传递到自定义视图 (SwiftUI)
- c# - HttpWebRequest StreamReader 失败,出现 utf-8 is not a supported encoding name 错误
- java - 未显示覆盖私有方法错误
- javascript - super() 上的打字稿错误:预期 1-2 个参数,但得到 0
- linux - Kubernetes - 本地存储 - nodeAffinity 不起作用
- java - 持久性上下文中的 EntityManager 不适用于 Spring Async 方法
- c++ - 在双精度向量上使用 C++ Eigen norm() 函数的问题
- php - 如何将数组的表单数据从角度发送到php脚本