如果我从构造函数中调用它,为什么我需要使Random对象静态?

时间:2012-03-21 21:27:48

标签: c#-4.0

class Student
{
    private string FirstName { get; set; }
    private string LastName { get; set; }
    private int age { get; set; }
    private int studentID { get; set; }
    private static int count = 0;
    **static Random randomNumber = new Random(); // works**
    **Random randomNumber = new Random();  // doesn't work I get the same studentID number**
    public Student()// constructor 
    {

        this.studentID = randomNumber.Next(1000000, 100000000);
        count++;
        Console.WriteLine("count {0}  studentID {1}", count, studentID);
    }

    public Student(string first, string last, int age)
    {

        this.studentID = randomNumber.Next(1000000, 100000000);
        count++; 
        Console.WriteLine("count {0}  studentID {1}", count, studentID);
        this.FirstName = first;
        this.LastName = last;
        this.age = age;
    }
   ...... continuation

    a few get methods

    ...... continuation

    public void PrintData()
    {
        Console.WriteLine("Name is {0}, Lastname is {1} , Age is {2} , studentID is  {3}", FirstName, LastName, age, this.studentID);
    }

为什么我会保持相同的数字,但如果我将Random对象设为静态,则会生成/分配新数字。不知道我的逻辑错在哪里。

1 个答案:

答案 0 :(得分:1)

如果您继续在构造函数中创建新的Random对象,它将重置种子(如果您不提供参数,则将种子设置为当前时间(请参阅:MSDN: Random constructor) - 因此,如果您创建多个随机物体彼此非常接近(在时间上)然后它将具有相同的种子)。由于Random不是真正随机的(如果你从同一个种子初始化它,你将总是得到相同的序列),你将在非静态版本中得到相同的数字。静态版本只创建一次,你不断询问序列中的下一个数字,因此它似乎给你实际的随机数。