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


当前回答

有许多实用程序函数或服务以与System.Random相同的方式更好地缓存,因此它适合于通用实现:

static public class CachedService<T> where T : new() {
    static public T Get { get; } = new T();
}

用于随机(或类似):

CachedService<System.Random>.Get.Next(999);

其他回答

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

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

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类(System.Random)生成的数字生成伪随机数。

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

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

这个问题看起来很简单,但答案有点复杂。如果你看到几乎所有人都建议使用Random类,有些人建议使用RNG加密类。但是,什么时候选择。

为此,我们需要首先理解随机性这一术语及其背后的哲学。

我鼓励大家观看我制作的这段视频,它使用C#深入探讨了随机性的哲学https://www.youtube.com/watch?v=tCYxc-2-3年

首先,让我们了解随机性的哲学。当我们告诉一个人在红色、绿色和黄色之间选择时,内部会发生什么。是什么让一个人选择红色、黄色或绿色?

一些最初的想法进入了人们的头脑,决定了他的选择,它可以是最喜欢的颜色,幸运的颜色等等。换句话说,一些最初的触发,我们在RANDOM中称之为SEED。这个SEED是起点,是促使他选择RANDOM值的触发。

现在,如果种子很容易猜测,那么这些随机数被称为伪随机数,而当种子很难猜测时,这些随机数则被称为安全随机数。

例如,一个人根据天气和声音组合选择颜色,那么很难猜出最初的种子。

现在让我发表一个重要声明:-

*“Random”类只生成PSEUDO随机数,要生成SECURE随机数,我们需要使用“RNGCryptoServiceProvider”类。

随机类从CPU时钟中获取种子值,这是非常可预测的。换句话说,C#的RANDOM类生成伪随机数,下面是相同的代码。

Random random = new Random();
int randomNumber = random.Next();

而RNGCryptoServiceProvider类使用OS熵生成种子。OS熵是一个随机值,使用声音、鼠标点击、键盘计时、温度等生成。下面是相同的代码。

using (RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider()) 
{ 
    byte[] rno = new byte[5];    
    rg.GetBytes(rno);    
    int randomvalue = BitConverter.ToInt32(rno, 0); 
}

要了解操作系统熵,请看我的视频,从14:30开始https://www.youtube.com/watch?v=tCYxc-2-3fY,其中解释了OS熵的逻辑。所以用简单的词RNG Crypto生成SECURE随机数。

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

using MiscUtil;
...

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