每次调用产生随机数函数的时候,总是产生同一组数据:

public static class GenericIListExtensions
   {
      public static T OneAtRandom<T>(this IList<T> list)
      {
         list.ThrowIfNull("list");
         if (list.Count == 0)
            throw new ArgumentException("OneAtRandom() cannot be called on 'list' with 0 elements");

         int randomIdx = new Random().Next(list.Count);
         return list[randomIdx];
      }
}

做如下的测试:

[Test]
        public void ShouldNotAlwaysReturnTheSameValueIfOneAtRandomCalledOnListOfLengthTwo()
        {
            int SomeStatisticallyUnlikelyNumberOf = 100;
            IList<string> list = new List<string>() { FirstString, SecondString };
            bool firstStringFound = false;
            bool secondStringFound = false;

            SomeStatisticallyUnlikelyNumberOf.Times(() =>
            {
                string theString = list.OneAtRandom();
                if (theString == FirstString) firstStringFound = true;
                if (theString == SecondString) secondStringFound = true;
            });
            Assert.That(firstStringFound && secondStringFound);
        }

`int randomIdx = new Random().Next(list.Count);'总是产生同样的一组数据,有没有什么办法让每次生成的随机数都不一样?

推荐图书

  • C#与.NET 4高级程序设计(第5版)


2个回答

MSDN有个例子,你可以参考:

int randomInstancesToCreate = 4;
Random[] randomEngines = new Random[randomInstancesToCreate];
for (int ctr = 0; ctr < randomInstancesToCreate; ctr++)
{
   randomEngines[ctr] = new Random(unchecked((int) (DateTime.Now.Ticks >> ctr)));
}

你不能每次都调用new Random(),这样会导致reseed从而产生一样的随机序列:

public static class GenericIListExtensions
{
      public static T OneAtRandom<T>(this IList<T> list, Random random)
      {
         list.ThrowIfNull("list");
         if (list.Count == 0)
            throw new ArgumentException("OneAtRandom() cannot be called on 'list' with 0 elements");

         int randomIdx = random.Next(list.Count);
         return list[randomIdx];
      }
}