简体   繁体   English

“非静态字段需要对象引用”

[英]"Object Reference is required for non-static field"

So I needed to make a random number generator for my minesweeper project, and I decided to put it in a method.所以我需要为我的扫雷项目制作一个随机数生成器,我决定把它放在一个方法中。

public static void GenerateBombs(int gsize, int numbombs, HashSet<int> numbers)
    {
        int num = gsize * gsize;
        while (numbers.Count < numbombs)
        {
            numbers.Add(Random.Next(1, num));
        }
    }

However I keep getting the "Object Reference needed for non-static field, property, or method."但是,我不断收到“非静态字段、属性或方法所需的对象引用”。 I don't know why and I can't figure it out from the other questions.我不知道为什么,我无法从其他问题中弄清楚。

Do like this:这样做:

private static Random rand = new Random();

public static void GenerateBombs(int gsize, int numbombs, HashSet<int> numbers)
{
    int num = gsize * gsize;
    while (numbers.Count < numbombs)
    {
        numbers.Add(rand.Next(1, num));
    }
}

The method Next() of the class Random is not a static method. class RandomNext()方法不是 static 方法。 You have to declare an instance of the class Random first:您必须先声明一个 class Random的实例:

static Random random = new Random();

then you can use it as numbers.Add(random.Next(1, num)) , now using the static instance of the class instead of the class itself.那么您可以将其用作numbers.Add(random.Next(1, num)) ,现在使用 class 的 static 实例而不是 class 本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM