如何在C#中生成随机整数?


当前回答

仅供参考。

如果您使用的是.NETCore,多个Random实例不会像以前那样危险。我知道这个问题是从2010年开始的,但由于这个问题很老,但有一些吸引力,我认为记录这一变化是一件好事。

你可以参考一下我刚才提出的这个问题:

Microsoft是否更改了随机默认种子?

基本上,他们已经将默认种子从Environment.TickCount更改为Guid.NewGuid().GetHashCode(),因此如果创建两个Random实例,它不应该显示相同的数字(1:4亿)。

您可以在此处查看.NET Framework/.NET Core(2.0.0+)的文件差异:https://github.com/dotnet/coreclr/pull/2192/commits/9f6a0b675e5ac0065a268554de49162c539ff66d

它不像RNGCryptoServiceProvider那样安全,但至少不会给你带来奇怪的结果。


作者@Enigmatility:

这已经过时了。反对使用Guids的声音相当强烈。代码现在是Interop.GetRandomBytes((byte*)&result,sizeof(int));

其他回答

除了COBOL答案,我已经尝试了所有这些解决方案。。。英雄联盟

这些解决方案都不够好。我需要一个快速的for int循环中的随机数,即使在很宽的范围内,我也得到了大量的重复值。在接受了太长时间的随机结果之后,我决定最终彻底解决这个问题。

这都是关于种子的。

我通过解析Guid中的非数字来创建一个随机整数,然后使用它来实例化random类。

public int GenerateRandom(int min, int max)
{
    var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
    return new Random(seed).Next(min, max);
}

更新:如果实例化Random类一次,则无需种子化。所以最好创建一个静态类并调用一个方法。

public static class IntUtil
{
   private static Random random;

   private static void Init()
   {
      if (random == null) random = new Random();
   }

   public static int Random(int min, int max)
   {
      Init();
      return random.Next(min, max);
   }
}

然后您可以像这样使用静态类。。

for(var i = 0; i < 1000; i++)
{
   int randomNumber = IntUtil.Random(1,100);
   Console.WriteLine(randomNumber); 
}

我承认我更喜欢这种方法。

创建随机对象

Random rand = new Random();

并使用它

int randomNumber = rand.Next(min, max);

你不必每次需要一个随机数时都初始化新的Random(),先初始化一个Random,然后在循环中使用它,或者其他

为什么不使用int randomNumber=Random.Range(start_Range,end_Range)?

Random random = new Random ();
int randomNumber = random.Next (lowerBound,upperBound);

如果您希望CSRNG生成最小值和最大值之间的随机数,这是适合您的。它将使用安全的随机种子初始化随机类。

    class SecureRandom : Random
    {
        public static byte[] GetBytes(ulong length)
        {
            RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider();
            byte[] bytes = new byte[length];
            RNG.GetBytes(bytes);
            RNG.Dispose();
            return bytes;
        }
        public SecureRandom() : base(BitConverter.ToInt32(GetBytes(4), 0))
        {

        }
        public int GetRandomInt(int min, int max)
        {
            int treashold = max - min;
            if(treashold != Math.Abs(treashold))
            {
                throw new ArithmeticException("The minimum value can't exceed the maximum value!");
            }
            if (treashold == 0)
            {
                throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
            }
            return min + (Next() % treashold);
        }
        public static int GetRandomIntStatic(int min, int max)
        {
            int treashold = max - min;
            if (treashold != Math.Abs(treashold))
            {
                throw new ArithmeticException("The minimum value can't exceed the maximum value!");
            }
            if(treashold == 0)
            {
                throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
            }
            return min + (BitConverter.ToInt32(GetBytes(4), 0) % treashold);
        }
    }