如何在C#中生成随机整数?
当前回答
您可以在他为伪随机数构建的MiscUtil类库中使用JonSkeet的StaticRandom方法。
using MiscUtil;
...
for (int i = 0; i < 100;
Console.WriteLine(StaticRandom.Next());
其他回答
Random r = new Random();
int n = r.Next();
从这里修改答案。
如果您可以访问与Intel Secure Key兼容的CPU,则可以使用以下库生成真正的随机数和字符串:https://github.com/JebteK/RdRand和https://www.rdrand.com/
只需从这里下载最新版本,包括Jebtek.RdRand并为其添加一个using语句。然后,您需要做的就是:
// Check to see if this is a compatible CPU
bool isAvailable = RdRandom.GeneratorAvailable();
// Generate 10 random characters
string key = RdRandom.GenerateKey(10);
// Generate 64 random characters, useful for API keys
string apiKey = RdRandom.GenerateAPIKey();
// Generate an array of 10 random bytes
byte[] b = RdRandom.GenerateBytes(10);
// Generate a random unsigned int
uint i = RdRandom.GenerateUnsignedInt();
如果您没有兼容的CPU来执行代码,只需使用rdrand.com上的RESTful服务即可。使用项目中包含的RdRandom包装库,您只需要这样做(注册时可以获得1000个免费调用):
string ret = Randomizer.GenerateKey(<length>, "<key>");
uint ret = Randomizer.GenerateUInt("<key>");
byte[] ret = Randomizer.GenerateBytes(<length>, "<key>");
为什么不使用int randomNumber=Random.Range(start_Range,end_Range)?
如其他答案中所述,一个好的安全方法是使用安全密码生成器。这里的所有示例都显示了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);
我想演示每次使用新的随机生成器时会发生什么。假设您有两个方法或两个类,每个都需要一个随机数。你天真地把它们编码成:
public class A
{
public A()
{
var rnd=new Random();
ID=rnd.Next();
}
public int ID { get; private set; }
}
public class B
{
public B()
{
var rnd=new Random();
ID=rnd.Next();
}
public int ID { get; private set; }
}
你认为你会得到两个不同的身份证吗?不
class Program
{
static void Main(string[] args)
{
A a=new A();
B b=new B();
int ida=a.ID, idb=b.ID;
// ida = 1452879101
// idb = 1452879101
}
}
解决方案是始终使用单个静态随机生成器。这样地:
public static class Utils
{
public static readonly Random random=new Random();
}
public class A
{
public A()
{
ID=Utils.random.Next();
}
public int ID { get; private set; }
}
public class B
{
public B()
{
ID=Utils.random.Next();
}
public int ID { get; private set; }
}
推荐文章
- 使用该集合的原因。种子功能
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?
- 如何使用try catch进行异常处理是最佳实践
- 替换字符串中第一次出现的模式
- .NET中字节的字面后缀?
- 如何处理AccessViolationException