如何在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);
}

其他回答

 int n = new Random().Next();

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

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

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

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

用于随机(或类似):

CachedService<System.Random>.Get.Next(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);
        }
    }
}

除了COBOL答案,我已经尝试了所有这些解决方案。。。英雄联盟

这些解决方案都不够好。我需要一个快速的for int循环中的随机数,即使在很宽的范围内,我也得到了大量的重复值。在接受了太长时间的随机结果之后,我决定最终彻底解决这个问题。

这都是关于种子的。

我通过解析Guid中的非数字来创建一个随机整数,然后使用它来实例化random类。

public int GenerateRandom(int min, int max)
{
    var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
    return new Random(seed).Next(min, max);
}

更新:如果实例化Random类一次,则无需种子化。所以最好创建一个静态类并调用一个方法。

public static class IntUtil
{
   private static Random random;

   private static void Init()
   {
      if (random == null) random = new Random();
   }

   public static int Random(int min, int max)
   {
      Init();
      return random.Next(min, max);
   }
}

然后您可以像这样使用静态类。。

for(var i = 0; i < 1000; i++)
{
   int randomNumber = IntUtil.Random(1,100);
   Console.WriteLine(randomNumber); 
}

我承认我更喜欢这种方法。