简体   繁体   中英

"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. You have to declare an instance of the class Random first:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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