简体   繁体   English

类方法中的随机数生成器

[英]Random number generator in a class method

This is part of a method inside of a class class. 这是类类中方法的一部分。 My goal is to generate a random number that number will be stored in a variable called iCell. 我的目标是生成一个随机数,该数字将存储在名为iCell的变量中。 After that, iCell will be used for the switch statement to change the character, cell. 之后,iCell将用于switch语句以更改字符,单元格。 I am getting an error from the iCell = Random.Next(1,9); 我从iCell = Random.Next(1,9);得到一个错误iCell = Random.Next(1,9); line that says "Error, An object reference is required for the non-static field, method, or property 'System.Random.Next(int, int)'". 这行说“错误,非静态字段,方法或属性'System.Random.Next(int,int)'需要对象引用”。 Is it not possible to have a random number generator in a class method? 类方法中不可能有随机数生成器吗?

 public void CPUMove() //method marks cell for CPU
    char cell;
    int iCell;
    Random rand = new Random();
    iCell = Random.Next(1, 9);
    switch (iCell)
    {
        case 1:
            cell = '1';
        break;
        case 2:
            cell = '2';
        break;
        case 3:
            cell = '3';
        break;
        case 4:
            cell = '4';
        break;
        case 5:
            cell = '5';
        break;
        case 6:
            cell = '6';
        break;
        case 7:
            cell = '7';
        break;
        case 8:
            cell = '8';
        break;
        case 9:
            cell = '9';
        break;
    }
iCell = rand.Next(1, 9);

Use the object you already created. 使用您已经创建的对象。

Please note that you should create this Random instance once in your program. 请注意,您应该在程序中一次创建此Random实例。 Maybe you can make it a class variable or even a static class variable. 也许您可以使其成为一个类变量,甚至是一个静态类变量。

You want rand.Next rather than Random.Next so that you're referencing the instance you just created 您需要rand.Next而不是Random.Next以便引用刚创建的实例

Also, you can get rid of that big switch statement. 另外,您可以摆脱大的switch语句。 Just write: 写吧:

cell = iCell.ToString()[0];

In addition to other answers: better off making the Random instance static. 除了其他答案:最好将Random实例设为静态。

class MyClass {
    static Random rand = new Random();

    public void CPUMove() { //method marks cell for CPU
        char cell;
        int iCell;
        iCell = rand.Next(1, 9);
        cell = iCell.ToString()[0];
    }
}

You can do it like that: 您可以这样做:

// Simplest case, not thread safe
// The same generator for all CPUMove() calls
private static Random rand = new Random();

// method marks cell for CPU
public void CPUMove() {
  // Don't re-create Random each time you need a random value:
  // the values generated will be badly skewed
  // Random rand = new Random();

  // You don't need any switch/case here, just a conversion 
  Char cell = (Char) (rand.Next('1', '9')); 
  ...
}

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

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