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


当前回答

重复使用Random的一个实例

// Somewhat better code...
Random rng = new Random();
for (int i = 0; i < 100; i++)
{
    Console.WriteLine(GenerateDigit(rng));
}
...
static int GenerateDigit(Random rng)
{
    // Assume there'd be more logic here really
    return rng.Next(10);
}

本文将探讨随机性为何会导致如此多的问题,以及如何解决这些问题。http://csharpindepth.com/Articles/Chapter12/Random.aspx

其他回答

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

Random r=new Random();
int Numbers=r.next(min value, max value);

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

快速方便的内联,使用以下代码:

new Random().Next(min, max);

// for example unique name
strName += "_" + new Random().Next(100, 999);

您可以在他为伪随机数构建的MiscUtil类库中使用JonSkeet的StaticRandom方法。

using MiscUtil;
...

for (int i = 0; i < 100; 
    Console.WriteLine(StaticRandom.Next());