在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#中更高效地生成隨機數。