为什么 System.Random 类不是静态的? [英] Why is the System.Random class not static?
问题描述
当您使用 System.Random
类时,您必须创建它的一个实例.为什么不是static
?因为如果我想要0到9之间的随机数,我可以使用静态方法,System.Random.Next(int, int)
:
When you use the System.Random
class, you must make an instance of it. Why is it not static
? Because if I want a random number between 0 and 9, I can use the static method, System.Random.Next(int, int)
:
int ourRandomNumber = Random.Next(0,9);
那么为什么类不只是static
?
推荐答案
如果它是静态的,您将无法使用不同的种子 - Random 实例会跟踪该状态.默认情况下 Random 使用当前时间作为种子,但重新使用特定的种子(即 new Random(42)
)允许您精确地重复随机数序列 - 它们将始终相同相同的种子.这方面在某些应用中非常重要.例如,我的世界.
You wouldn't be able to use different seeds if it were static - the Random instance keeps track of that state.
By default Random uses the current time as seed, but re-using a particular seed (i.e. new Random(42)
) allows you to exactly repeat the sequence of random numbers - they will always be the same for the same seed. This aspect is very important in some applications. For example, Minecraft.
这篇关于为什么 System.Random 类不是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!