Correct method of a “static” Random.Next in C#?

前端 未结 11 2215
执念已碎
执念已碎 2020-12-10 10:51

Why do i need to create an instance of Random class, if i want to create a random number between 1 and 100 ....like

Random rand = new Random();
rand.Next(1,1         


        
11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 11:31

    Why not?

    You need to create an instance because the way random numbers are generated is that previous answers affect subsequent answers. By default, the new Random() constructor uses the current system time to "seed" the sequence, but it doesn't have to: you can pass your own number in if you like. In particular:

    var rand = new Random(1234);
    Console.WriteLine(rand.Next(0, 100));
    Console.WriteLine(rand.Next(0, 100));
    Console.WriteLine(rand.Next(0, 100));
    Console.WriteLine(rand.Next(0, 100));
    

    Will produce the same sequence of "random" number every time.

    That means the Random class needs to keep instance data (the previous answer, or "seed") around for subsequent calls.

提交回复
热议问题