一、简单生成(Random)
Random算法简单,性能较高,适用于随机性要求不高的情况
for(int i=0;i<10;i++) { Random rd = new Random(); Console.WriteLine(rd.Next(10,100).ToString()); }
二、提高型Random
以guid作为随机因子传入random
三、RNGCryptoServiceProvider
System.Security.Cryptography.RNGCryptoServiceProvider
RNGCryptoServiceProvider在生成期间需要查询上面提到的几种系统因子
public static string GetRandomString(int length, bool useNum=false, bool useLow=false, bool useUpp=false, bool useSpe=false)
{
byte[] b = new byte[4];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
Random r = new Random(BitConverter.ToInt32(b, 0));
string s = null, str = "";
if (useNum == true) { str += "0123456789"; }
if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
for (int i = 0; i < length; i++)
{
s += str.Substring(r.Next(0, str.Length - 1), 1);
}
return s;
}