C#生成随机数(c#生成随机数0-100内100位)
在C#中生成随机数主要有以下几种方法,适用于不同场景:
一、基础Random类(通用场景)
Random rnd = new Random();
int randomInt = rnd.Next(); // 0到Int32.MaxValue的随机整数
int randomRange = rnd.Next(10, 100); // 10到99的随机整数
double randomDouble = rnd.NextDouble(); // 0.0到1.0的随机浮点数
- 特点:简单易用,但不适合加密或高安全需求场景。
二、安全随机数生成(加密场景)
使用
System.Security.Cryptography命名空间的RNGCryptoServiceProvider:
using System.Security.Cryptography;
byte[] buffer = new byte;
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(buffer);
int secureInt = BitConverter.ToInt32(buffer);
}
- 特点:基于操作系统加密算法,适合生成密码、密钥等敏感数据。
三、LINQ扩展方法(灵活生成)
通过LINQ结合Random类生成特定集合:
var randomNumbers = Enumerable.Range(0, 10)
.OrderBy(x => rnd.Next())
.Take(5); // 随机选取5个不重复的数
- 特点:适合需要随机排序或抽样的场景。
四、第三方库(高性能需求)
- Accord.NET:提供高斯分布、泊松分布等统计随机数生成。
- System.Random.Boost:支持并行生成随机数,提升多线程性能。
五、注意事项
1. 避免重复种子:若频繁创建Random实例,需使用DateTime.Now.Ticks作为种子避免重复。
2. 多线程场景:建议使用ThreadLocal<Random>或ConcurrentRandom类。