您可以使用 RNGCryptoServiceProvider 从 System.Random 继承来获取数字,但您必须小心,因为您需要覆盖很多方法:
/*
[MSDN]
Notes to Inheritors:
In the .NET Framework versions 1.0 and 1.1, a minimum implementation of
a class derived from Random required overriding the Sample method
to define a new or modified algorithm for generating random numbers.
The derived class could then rely on the base class implementation
of the Random.Next(), Random.Next(Int32), Random.Next(Int32, Int32),
NextBytes, and NextDouble methods to call the derived class implementation of the Sample method.
In the .NET Framework version 2.0 and later, the behavior of the Random.Next(),
Random.Next(Int32, Int32), and NextBytes methods have changed
so that these methods do not necessarily call the derived class implementation
of the Sample method.
As a result, classes derived from Random that target the .NET Framework 2.0
and later should also override these three methods.
*/
class CryptoRandom : System.Random {
private RandomNumberGenerator rng;
public CryptoRandom() {
rng = new RNGCryptoServiceProvider();
}
public override int Next() {
byte[] bytes = new byte[4];
rng.GetBytes(bytes);
return int.MaxValue & BitConverter.ToInt32(bytes, 0);
}
public override void NextBytes(byte[] b)
{
rng.GetBytes(b);
}
public override int Next(int lo, int hi){
throw new Exception("TODO override (arc4random_uniform is beautiful)");
}
protected override double Sample()
{
throw new Exception("TODO override");
}
}
或者,由于您将使用所有这些来获取一个小的(长度<=255)字符串的索引,您可以直接使用字节来获取其中的索引(避免模偏差,这就是我写这个答案的原因首先 - 请参阅 http://BXR.SU/OpenBSD/lib/libc/crypt/arc4random_uniform.c#arc4random_uniform 上的arc4random_uniform)。