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


当前回答

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

其他回答

这是我使用的类。工作方式类似RandomNumber.GenerateRandom(1666)

internal static class RandomNumber
{
    private static Random r = new Random();
    private static object l = new object();
    private static Random globalRandom = new Random();
    [ThreadStatic]
    private static Random localRandom;
    public static int GenerateNewRandom(int min, int max)
    {
        return new Random().Next(min, max);
    }
    public static int GenerateLockedRandom(int min, int max)
    {
        int result;
        lock (RandomNumber.l)
        {
            result = RandomNumber.r.Next(min, max);
        }
        return result;
    }
    public static int GenerateRandom(int min, int max)
    {
        Random random = RandomNumber.localRandom;
        if (random == null)
        {
            int seed;
            lock (RandomNumber.globalRandom)
            {
                seed = RandomNumber.globalRandom.Next();
            }
            random = (RandomNumber.localRandom = new Random(seed));
        }
        return random.Next(min, max);
    }
}

如其他答案中所述,一个好的安全方法是使用安全密码生成器。这里的所有示例都显示了RNGCryptoServiceProvider的用法,与我建议的解决方案相比,它编写的代码很长。

使用RandomNumberGenerator,它是在密码学API之上编写的。它和RNGCryptoServiceProvider一样安全,并且具有相同的随机性。

// Gives a random number for the integer range.
// You can simply update the parameters as your needs.
RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);

仅供参考。

如果您使用的是.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));

我想演示每次使用新的随机生成器时会发生什么。假设您有两个方法或两个类,每个都需要一个随机数。你天真地把它们编码成:

public class A
{
    public A()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}

你认为你会得到两个不同的身份证吗?不

class Program
{
    static void Main(string[] args)
    {
        A a=new A();
        B b=new B();

        int ida=a.ID, idb=b.ID;
        // ida = 1452879101
        // idb = 1452879101
    }
}

解决方案是始终使用单个静态随机生成器。这样地:

public static class Utils
{
    public static readonly Random random=new Random();
}

public class A
{
    public A()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}
Random r = new Random();
int n = r.Next();