随机数生成

一个小小的随机数生成

/// <summary> /// lou 2019-9-25 15:14:02 生成随机字符串 /// </summary> /// <param name="length">返回值的长度</param> /// <param name="type">返回值类型,1:纯数字;2:小写字母;3:大写字母;4:大小写字母混合;5:小写字母和数字混合;6:大写字母和数字混合;7:大小写字母和数字混合</param> /// <returns></returns> public static string GetCode(int length, int type) { string str = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ"; string retStr = ""; Random rnd = new Random(GetRandomSeed()); for (int i = 0; i < length; i++) { switch (type) { case 1: retStr += rnd.Next(10).ToString(); break; case 2: retStr += str.Substring(10 + rnd.Next(26), 1); break; case 3: retStr += str.Substring(36 + rnd.Next(26), 1); break; case 4: retStr += str.Substring(10 + rnd.Next(52), 1); break; case 5: retStr += str.Substring(0 + rnd.Next(36), 1); break; case 6: retStr += str.Substring(0 + rnd.Next(36), 1).ToUpper(); break; case 7: retStr += str.Substring(0 + rnd.Next(61), 1); break; } } if (retStr == "") { retStr = GetCode(length, type); } return retStr; } /// <summary> /// 描 述:创建加密随机数生成器 生成强随机种子 /// </summary> /// <returns></returns> private static int GetRandomSeed() { byte[] bytes = new byte[4]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); }

 

上一篇:QT 二维图形 原理、发展及应用


下一篇:Java集合-单例模式斗地主&Collections类的shuffle方法了解