在C#中,生成随机数的常用方法是使用System.Random
类
public static class RandomHelper
{
private static readonly Random _random = new Random();
public static int GetRandomNumber(int min, int max)
{
return _random.Next(min, max);
}
}
System.Security.Cryptography.RNGCryptoServiceProvider
生成密码学安全的随机数:当需要生成加密安全的随机数时,可以使用RNGCryptoServiceProvider
类。using System.Security.Cryptography;
public static class CryptoRandomHelper
{
public static int GetCryptoRandomNumber(int min, int max)
{
using var rng = new RNGCryptoServiceProvider();
var randomNumber = new byte[4];
rng.GetBytes(randomNumber);
int fullRange = max - min;
int result = BitConverter.ToInt32(randomNumber, 0) % fullRange + min;
return result;
}
}
Random.NextGaussian
扩展方法生成正态分布的随机数。public static class GaussianRandomHelper
{
public static double NextGaussian(this Random random, double mean, double stdDev)
{
double u1 = random.NextDouble();
double u2 = random.NextDouble();
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
return mean + stdDev * randStdNormal;
}
}
Fisher-Yates
算法对一个有序的整数序列进行随机排序。public static class UniqueRandomNumbersHelper
{
public static IEnumerable<int> GetUniqueRandomNumbers(int count, int min, int max)
{
if (count > max - min + 1)
throw new ArgumentOutOfRangeException(nameof(count), "Count is too large.");
var numbers = Enumerable.Range(min, max - min + 1).ToList();
var random = new Random();
for (int i = numbers.Count - 1; i >= 0; i--)
{
int j = random.Next(i + 1);
yield return numbers[j];
numbers[j] = numbers[i];
}
}
}
这些技巧可以帮助你在C#中更高效地生成随机数。