正确的方法和QUOT;静态" Random.Next在C#中? [英] Correct method of a "static" Random.Next in 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.
这篇关于正确的方法和QUOT;静态" Random.Next在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!