2011-06-16 78 views
5

举例来说,如果我有一个类:如何在一行中有两个随机数给出不同的值?

public class Class 
{ 
public Random r; 

public Class() 
{r= new Random()} 
} 

后来创建它的两个实例:

Class a = new Class(); 
Class b = new Class(); 

,并调用顺序R,同时为R将给予相同的值。我读过这是因为Random的默认构造函数使用时间来提供“随机性”,所以我想知道如何防止这种情况。提前致谢!

回答

5

实现该目的的一种方法是制作rstatic

static意味着只有一个Random r将存在,它将在该类的所有实例中共享。

你的代码应该是这样的:

public class Class() { static Random r = new Random(); } 

Class a = new Class(); 
Class b = new Class(); 

如果你使用线程,你可以把它[ThreadStatic](这样每个线程使用自己的Random类的实例)

有信息关于如何使用[ThreadStatic]here - 我自己并没有使用它,但它看起来很酷且漂亮,并且摆脱了任何潜在的线程相关的困境。

4

随机类的构造函数是基于时间的。所以当你以快速的顺序创建它们时 - 它们会得到相同的种子,然后会产生相同的值。

所以你需要分享你的课程的随机- 或 -你自己提供一个不同的初始种子。

2

在这种情况下的一种可能性是使Random成为一个静态,以便它只被实例化一次。

public class Class{ 
    private static Random r = new Random();   
    //the rest of your class 
} 

的问题是,您所创建的两个类几乎在同一时间,因此他们将使用相同的种子(因为它是基于中其他事物的当前时间),并会产生相同的数字序列。

1

试试这个:

public class TestClass 
{ 
    private static int seed = Environment.TickCount; 


    public TestClass() 
    { 
     DoStuff(); 
     DoStuff(); 
     DoStuff(); 
     DoStuff(); 
    } 

    private void DoStuff() 
    { 
     var random = new Random(seed++); 
     int index = random.Next(30) + 1; 

     //Console.Write(index); 
    } 
} 
相关问题