字符串,随机,有趣的行为

时间:2012-10-22 16:52:38

标签: c# .net random stringbuilder

  

可能重复:
  why does this method return the same random string each time?
  Random not that random

我在这段代码中有奇怪的行为。

public void InitPopulation()
{
    for (int i = 0; i < PopSize; i++)
    {
        var builder = new StringBuilder();
        var random = new Random();

        for (int j = 0; j < Target.Length; j++)
        {
            builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));
        }

                        vector.Add(new GaStruct() { Fitness = 0, StrValue = builder.ToString().ToLower() });
        builder.Clear();
    }
}

这段代码给了我5个完全相同的字符串!

如果我像这样添加Thread.Sleep

public void InitPopulation()
{
    for (int i = 0; i < PopSize; i++)
    {
        var builder = new StringBuilder();
        var random = new Random();

        for (int j = 0; j < Target.Length; j++)
        {
            builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));
        }

        **System.Threading.Thread.Sleep(20);**
        vector.Add(new GaStruct() { Fitness = 0, StrValue = builder.ToString().ToLower() });
        builder.Clear();
    }
}

一切都很好,所有字符串都是随机的。

0 个答案:

没有答案