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


当前回答

我想添加一个加密安全版本:

RNGCryptoServiceProvider类(MSDN或dotnetperls)

它实现了IDisposable。

using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
   byte[] randomNumber = new byte[4];//4 for int32
   rng.GetBytes(randomNumber);
   int value = BitConverter.ToInt32(randomNumber, 0);
}

其他回答

内置Random类(System.Random)生成的数字生成伪随机数。

如果你想要真正的随机数,我们最接近的就是“安全伪随机生成器”,它可以通过使用C#中的Cryptographic类(如RNGCryptoServiceProvider)生成。

即使如此,如果你仍然需要真正的随机数,你将需要使用一个外部源,比如解释放射性衰变的设备,作为随机数发生器的种子。因为,根据定义,任何纯算法产生的数字都不可能是真正随机的。

如果您希望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);
        }
    }

每次执行新的Random()时,它都会初始化。这意味着在一个紧密的循环中,你会多次获得相同的值。您应该保留一个Random实例,并在同一实例上继续使用Next。

//Function to get random number
private static readonly Random getrandom = new Random();

public static int GetRandomNumber(int min, int max)
{
    lock(getrandom) // synchronize
    {
        return getrandom.Next(min, max);
    }
}

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

请注意,新的Random()是在当前时间戳上播种的。

如果您只想生成一个数字,可以使用:

new Random().Next(int.MinValue,int.MaxValue)

有关更多信息,请查看Random类,但请注意:

然而,由于时钟具有有限的分辨率,使用无参数构造器来连续创建不同的随机对象会创建随机数生成器,生成相同的随机数序列

因此,不要使用此代码生成一系列随机数。