正确的方法和QUOT;静态" Random.Next在C#中?

问题描述:

为什么我需要创建Random类的实例,如果我想创建1和100之间的随机数....像

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,100);

有Random类的任何静态函数做一样的吗?像...

Is there any static function of Random class to do the same? like...

Random.Next(1,100);



我不想不必要地创建一个实例

I don't want to create an instance unnecessarily

这是创建随机的单个实例,并用它在你的程序的最佳实践 - 否则结果可能不作为随机的。这种行为是不是创建一个静态函数鼓励

It is best practice to create a single instance of Random and use it throughout your program - otherwise the results may not be as random. This behavior is encouraged by not creating a static function.

您不应该担心不必要地创建一个实例,影响充其量是微不足道的 - 这是方法该框架的工作。

You shouldn't worry about "creating an instance unnecessarily", the impact is negligible at best - this is the way the framework works.