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


当前回答

创建随机对象

Random rand = new Random();

并使用它

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

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

其他回答

如果您希望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 r = new Random();
int n = r.Next();

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

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

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

对于强随机种子,我总是使用CryptoRNG而不是时间。

using System;
using System.Security.Cryptography;

public class Program
{
    public static void Main()
    {
        var random = new Random(GetSeed());
        Console.WriteLine(random.Next());
    }

    public static int GetSeed() 
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            var intBytes = new byte[4];
            rng.GetBytes(intBytes);
            return BitConverter.ToInt32(intBytes, 0);
        }
    }
}
 int n = new Random().Next();

您还可以为Next()函数指定最小值和最大值。喜欢:

 int n = new Random().Next(5, 10);