[英]Why does this run in Visual Studio 2019 but not 2022? Method in c#
尝试学习 c# 中的方法/函数,但这段代码由于某种原因无法运行,但它确实可以在 visual studio 2019 中运行。
编辑:添加了我在下面遇到的错误
static int ThrowDice(int slag)
{
return ThrowDice(6, slag);
}
static int ThrowDice(int sidor, int slag)
{
int resultat = 0;
Random rnd = new Random();
for (int i = 0; i < slag; i++)
{
int varjekast = rnd.Next(1, sidor + 1);
Console.WriteLine($"kast{i+1} blir {varjekast}");
resultat += varjekast;
}
return resultat;
}
Console.WriteLine("Ange tärningens antal sidor: ");
int sidor = int.Parse(Console.ReadLine());
Console.WriteLine("Ange tärningskast: ");
int kast = int.Parse(Console.ReadLine());
Console.WriteLine("Resultat: " + ThrowDice(sidor, kast));
Console.ReadLine();
我得到的错误:
Severity Code Description Project File Line Suppression State
Error CS1501 No overload for method 'ThrowDice' takes 2 arguments
Severity Code Description Project File Line Suppression State
Error CS8422 A static local function cannot contain a reference to 'this' or 'base'.
Severity Code Description Project File Line Suppression State
Error CS0128 A local variable or function named 'ThrowDice' is already defined in this scope
Severity Code Description Project File Line Suppression State
Error CS1501 No overload for method 'ThrowDice' takes 2 arguments Rollspel2
正如您的错误消息告诉您的那样,您不能对具有相同名称的本地函数进行 delcare:
Error CS0128 A local variable or function named 'ThrowDice' is already defined in this scope
所以你需要给它们起不同的名字,或者像这样把它们放在 class 中
Console.WriteLine ("Ange tärningens antal sidor: ");
int sidor = int.Parse (Console.ReadLine ());
Console.WriteLine ("Ange tärningskast: ");
int kast = int.Parse (Console.ReadLine ());
Console.WriteLine ("Resultat: " + new Dice().ThrowDice (sidor, kast));
public class Dice
{
public int ThrowDice (int slag)
{
return ThrowDice (6, slag);
}
public int ThrowDice (int sidor, int slag)
{
int resultat = 0;
Random rnd = new Random ();
for (int i = 0; i < slag; i++)
{
int varjekast = rnd.Next (1, sidor + 1);
Console.WriteLine ($"kast{i + 1} blir {varjekast}");
resultat += varjekast;
}
return resultat;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.