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


当前回答

请注意,新的Random()是在当前时间戳上播种的。

如果您只想生成一个数字,可以使用:

new Random().Next(int.MinValue,int.MaxValue)

有关更多信息,请查看Random类,但请注意:

然而,由于时钟具有有限的分辨率,使用无参数构造器来连续创建不同的随机对象会创建随机数生成器,生成相同的随机数序列

因此,不要使用此代码生成一系列随机数。

其他回答

对于强随机种子,我总是使用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);
        }
    }
}

抱歉,OP确实需要一个随机整型值,但为了分享知识,如果您想要一个随机BigInteger值,可以使用以下语句:

BigInteger randomVal = BigInteger.Abs(BigInteger.Parse(Guid.NewGuid().ToString().Replace("-",""), NumberStyles.AllowHexSpecifier));

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

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

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

仅供参考。

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