“Expression denotes a `variable', where a `method group' was expected”这句话是什么意思?

3

我作为一个初学者正在学习c#,并编写了一个程序,可以向用户提供一个骰子随机数,直到获得六为止。以下是我的完整代码:

using System;

class HelloWorld {
  static void Main() {
        Random numberGen = new Random();

        int roll = 0;
        int attempts = 0;

        Console.WriteLine("Press enter to roll the die");

        while (roll != 6) {
            Console.ReadKey();

            roll = numberGen(1, 7);
            Console.WriteLine("You rolled " + roll);
            attempts++;
        }

        Console.WriteLine("It took you " + attempts + " to roll a six");
        Console.ReadLine();
  }
}

我做错了什么,如何调试它?

4
numberGen(1, 7) 应该改为 numberGen.Next(1, 7)。详见文档。另外,如果你想让用户“按回车键”,请使用Console.ReadLine()而不是Console.ReadKey()。后者会接受 任何 按键,而不仅仅是回车键。 - 41686d6564 stands w. Palestine
3个回答

2
问题出在这里:
roll = numberGen(1, 7);

只有当变量是一个类型化的委托时,你才能使用variable(...)语法(在这种情况下,编译器会将其解释为variable.Invoke(...))。在所有其他情况下,预期您通过变量访问某些方法/属性/字段/索引器/事件,使用其中之一:variable.Foo(...)variable.Foovariable[index](如果变量是未管理的指针,则使用->代替.)。
在这种情况下,您需要:
roll = numberGen.Next(1, 7);

1

在您的代码中,您创建了一个名为“numberGen”的变量。由于它是“Random”类的变量,您需要使用此变量调用该类的方法,例如 -

numberGen.Next(1,7);

'Next'是Random类的方法,接受两个参数:最小值和最大值。

你之前遇到的错误是因为你将变量当作了方法使用。


0

在编程中生成随机数的默认方法是:

Random rnd = new Random();
rnd.Next(1, 10);

在你的情况下,只需更新变量即可。
roll = numberGen(1, 7);

to:

roll = numberGen.Next(1, 7);

Random - 它是一个类。 Next - 它是一个方法。

  • 关于 C# 中的,请点击这里了解更多
  • 关于 C# 中的方法,请点击这里了解更多
  • 关于 Random 类,请点击这里了解更多

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接