如何在C#中生成随机整数?
当前回答
根据定义,由计算机通过确定性过程计算的数字不能是随机的。
如果你想要一个真正的随机数,随机性来自大气噪声或放射性衰变。
例如,您可以尝试RANDOM.ORG(它会降低性能)
其他回答
您可以在他为伪随机数构建的MiscUtil类库中使用JonSkeet的StaticRandom方法。
using MiscUtil;
...
for (int i = 0; i < 100;
Console.WriteLine(StaticRandom.Next());
Random rand = new Random();
int name = rand.Next()
在第二个括号中放入所需的值确保通过编写prop和double tab来设置名称以生成代码
有许多实用程序函数或服务以与System.Random相同的方式更好地缓存,因此它适合于通用实现:
static public class CachedService<T> where T : new() {
static public T Get { get; } = new T();
}
用于随机(或类似):
CachedService<System.Random>.Get.Next(999);
Random random = new Random ();
int randomNumber = random.Next (lowerBound,upperBound);
如果您希望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);
}
}
推荐文章
- Selenium c# WebDriver:等待元素出现
- 我如何添加双引号的字符串,是在一个变量?
- 从枚举中选择一个随机值?
- 检查字符串是否包含字符串列表中的元素
- 我如何在c++中创建一个随机的字母数字字符串?
- 从集合中随机选取一个元素
- 最好的方法在asp.net强制https为整个网站?
- 将字符串转换为System.IO.Stream
- Java生成两个给定值之间的随机数
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API