如何在C#中生成随机整数?
当前回答
我想添加一个加密安全版本:
RNGCryptoServiceProvider类(MSDN或dotnetperls)
它实现了IDisposable。
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] randomNumber = new byte[4];//4 for int32
rng.GetBytes(randomNumber);
int value = BitConverter.ToInt32(randomNumber, 0);
}
其他回答
int n = new Random().Next();
您还可以为Next()函数指定最小值和最大值。喜欢:
int n = new Random().Next(5, 10);
Random r = new Random();
int n = r.Next();
有许多实用程序函数或服务以与System.Random相同的方式更好地缓存,因此它适合于通用实现:
static public class CachedService<T> where T : new() {
static public T Get { get; } = new T();
}
用于随机(或类似):
CachedService<System.Random>.Get.Next(999);
对于强随机种子,我总是使用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);
}
}
}
除了COBOL答案,我已经尝试了所有这些解决方案。。。英雄联盟
这些解决方案都不够好。我需要一个快速的for int循环中的随机数,即使在很宽的范围内,我也得到了大量的重复值。在接受了太长时间的随机结果之后,我决定最终彻底解决这个问题。
这都是关于种子的。
我通过解析Guid中的非数字来创建一个随机整数,然后使用它来实例化random类。
public int GenerateRandom(int min, int max)
{
var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
return new Random(seed).Next(min, max);
}
更新:如果实例化Random类一次,则无需种子化。所以最好创建一个静态类并调用一个方法。
public static class IntUtil
{
private static Random random;
private static void Init()
{
if (random == null) random = new Random();
}
public static int Random(int min, int max)
{
Init();
return random.Next(min, max);
}
}
然后您可以像这样使用静态类。。
for(var i = 0; i < 1000; i++)
{
int randomNumber = IntUtil.Random(1,100);
Console.WriteLine(randomNumber);
}
我承认我更喜欢这种方法。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 如何在Ruby中生成a和b之间的随机数?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?