整理随机数、随机字符串的生成方法:
1 #region 生成随机数字 2 /// <summary> 3 /// 生成随机数字 4 /// </summary> 5 /// <param name="length">生成长度</param> 6 /// <returns></returns> 7 public static string Number(int length) 8 { 9 return Number(length, false); 10 } 11 #endregion 12 13 #region 生成随机数字(有线程睡眠时间) 14 /// <summary> 15 /// 生成随机数字(有线程睡眠时间) 16 /// </summary> 17 /// <param name="length">生成随机数的长度</param> 18 /// <param name="sleep">是否要在生成前将当前线程阻止以避免重复</param> 19 /// <param name="millisecondsTimeout">线程睡眠时间</param> 20 /// <returns></returns> 21 public static string Number(int length, bool sleep, int millisecondsTimeout = 3) 22 { 23 if (sleep) 24 { 25 System.Threading.Thread.Sleep(millisecondsTimeout); 26 } 27 string result = ""; 28 System.Random random = new Random(); 29 for (int i = 0; i < length; i++) 30 { 31 result += random.Next(10).ToString(); 32 } 33 return result; 34 } 35 #endregion 36 37 #region 生成随机字母字符串(数字字母混和) 38 /// <summary> 39 /// 生成随机字母字符串(数字字母混和) 40 /// </summary> 41 /// <param name="length">待生成的随机数位数</param> 42 /// <returns></returns> 43 public static string GetNumberCode(int length) 44 { 45 string str = string.Empty; 46 int rep = 0; 47 long num2 = DateTime.Now.Ticks + rep; 48 rep++; 49 Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep))); 50 for (int i = 0; i < length; i++) 51 { 52 char ch; 53 int num = random.Next(); 54 if ((num % 2) == 0) 55 { 56 ch = (char)(0x30 + ((ushort)(num % 10))); 57 } 58 else 59 { 60 ch = (char)(0x41 + ((ushort)(num % 0x1a))); 61 } 62 str = str + ch.ToString(); 63 } 64 return str; 65 } 66 #endregion