生成的随机数总是相等 [英] Generated random numbers are always equal
问题描述
我有一个类:
public class MyClass
{
public int MyMethod()
{
Random rand = new Random();
return rand.Next() % 10 + 1;
}
}
和它的两个对象:
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
问题是, obj1.MyMethod()== obj2.MyMethod()
始终。为什么会发生?什么是避免它的最佳方式?
The problem is that obj1.MyMethod() == obj2.MyMethod()
always. Why does it happen? What's the best way to avoid it?
推荐答案
创建随机对象的静态
public class MyClass
{
public static Random rand = new Random();
public int MyMethod()
{
return rand.Next() % 10 + 1;
}
}
随机适用于 System.DatTime.Now.Ticks
。
如果我们做这样的
Random rand = new Random();
在内部它发生,因为
internally it happens as
Random rand = new Random(System.DateTime.Now.Ticks);
试想想了一会儿这是不是在不断的系统的唯一事情是系统时间。
Just think for a moment the only thing which is not constant in system is System Time.
在使用过Random类使其对象一次,并使用它的方法下一页()
任何你想去的地方。当内部循环创建随机对象,你会发现在循环中这种情况。
When ever using Random class make its object once and use its method Next()
where ever you want. You will find this situation in loops when random object is created inside loops.
在您的code他们创造了一个又一个,他们以同样的蜱的种子值创建的。
In your code they are created one after another, they get created by same Ticks seed value.
创建随机对象的静态,然后他们将不一样的。
Create your random object static and then they won't be same.
这篇关于生成的随机数总是相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!