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


当前回答

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

其他回答

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

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

using MiscUtil;
...

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

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

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

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

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