如何在C#中生成随机整数?
当前回答
Random r = new Random();
int n = r.Next();
其他回答
如果您希望CSRNG生成最小值和最大值之间的随机数,这是适合您的。它将使用安全的随机种子初始化随机类。
class SecureRandom : Random
{
public static byte[] GetBytes(ulong length)
{
RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider();
byte[] bytes = new byte[length];
RNG.GetBytes(bytes);
RNG.Dispose();
return bytes;
}
public SecureRandom() : base(BitConverter.ToInt32(GetBytes(4), 0))
{
}
public int GetRandomInt(int min, int max)
{
int treashold = max - min;
if(treashold != Math.Abs(treashold))
{
throw new ArithmeticException("The minimum value can't exceed the maximum value!");
}
if (treashold == 0)
{
throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
}
return min + (Next() % treashold);
}
public static int GetRandomIntStatic(int min, int max)
{
int treashold = max - min;
if (treashold != Math.Abs(treashold))
{
throw new ArithmeticException("The minimum value can't exceed the maximum value!");
}
if(treashold == 0)
{
throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
}
return min + (BitConverter.ToInt32(GetBytes(4), 0) % treashold);
}
}
如其他答案中所述,一个好的安全方法是使用安全密码生成器。这里的所有示例都显示了RNGCryptoServiceProvider的用法,与我建议的解决方案相比,它编写的代码很长。
使用RandomNumberGenerator,它是在密码学API之上编写的。它和RNGCryptoServiceProvider一样安全,并且具有相同的随机性。
// Gives a random number for the integer range.
// You can simply update the parameters as your needs.
RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);
仅供参考。
如果您使用的是.NETCore,多个Random实例不会像以前那样危险。我知道这个问题是从2010年开始的,但由于这个问题很老,但有一些吸引力,我认为记录这一变化是一件好事。
你可以参考一下我刚才提出的这个问题:
Microsoft是否更改了随机默认种子?
基本上,他们已经将默认种子从Environment.TickCount更改为Guid.NewGuid().GetHashCode(),因此如果创建两个Random实例,它不应该显示相同的数字(1:4亿)。
您可以在此处查看.NET Framework/.NET Core(2.0.0+)的文件差异:https://github.com/dotnet/coreclr/pull/2192/commits/9f6a0b675e5ac0065a268554de49162c539ff66d
它不像RNGCryptoServiceProvider那样安全,但至少不会给你带来奇怪的结果。
作者@Enigmatility:
这已经过时了。反对使用Guids的声音相当强烈。代码现在是Interop.GetRandomBytes((byte*)&result,sizeof(int));
内置Random类(System.Random)生成的数字生成伪随机数。
如果你想要真正的随机数,我们最接近的就是“安全伪随机生成器”,它可以通过使用C#中的Cryptographic类(如RNGCryptoServiceProvider)生成。
即使如此,如果你仍然需要真正的随机数,你将需要使用一个外部源,比如解释放射性衰变的设备,作为随机数发生器的种子。因为,根据定义,任何纯算法产生的数字都不可能是真正随机的。
为什么不使用int randomNumber=Random.Range(start_Range,end_Range)?
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制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>?