1
//生成23位的随机数
public class RandomHash 2 { 3 public static System.Collections.Generic.Dictionary<string, HashSet<string>> Hashtable = new Dictionary<string, HashSet<string>>(); 4 5 /// <summary> 6 /// Check digit(模10) 7 /// </summary> 8 /// <param name="num"></param> 9 /// <returns></returns> 10 public static string Genchecknum(string num) 11 { 12 string result = string.Empty; 13 try 14 { 15 if (num.Length == 22) 16 { 17 int sum = 0; 18 for (int i = 0; i < 22; i++) 19 { 20 int dit = 0; 21 //is Odd 22 if (Convert.ToBoolean(i % 2)) 23 { 24 dit = int.Parse(num.Substring(i, 1)) * 2; 25 if (dit > 9) 26 dit = dit - 9; 27 } 28 else 29 { 30 dit = int.Parse(num.Substring(i, 1)); 31 } 32 sum = sum + dit; 33 } 34 double doublesum = Math.Ceiling(Convert.ToDouble(sum) / 10) * 10; 35 result = (doublesum - sum).ToString(); 36 } 37 } 38 catch 39 { 40 } 41 return result; 42 } 43 44 public static string GenRandom(string acct, string country, string type, string tranName) 45 { 46 string refnum = string.Empty; 47 Random random = new Random(); 48 DateTime dt = DateTime.Now; 49 string acctnum = string.Empty; 50 string prefix = string.Empty; 51 string fieldType = string.Empty; 52 string binNum = string.Empty; 53 try 54 { 55 prefix = "7"; 56 acctnum = binNum == null ? acct.Substring(0, 6) : binNum; 57 } 58 catch (Exception ex) 59 { 60 throw ex; 61 } 62 string ID = dt.ToString("yyyyMMddHHmmss"); 63 { 64 if (Hashtable.ContainsKey(ID)) 65 { 66 bool isnotunique = true; 67 int runnum = 0; 68 do 69 { 70 string ran = random.Next(99999).ToString("00000"); 71 //refNum 由站位数字prefix + acct账号的前6位 + 年份的最后一位数字 + 当天是当年的第多少天 + 当前的HHmmss + 五位的随机数, 以及 校验生成的一位数字 72 refnum = prefix + acctnum + dt.Year.ToString().Substring(3, 1) + dt.DayOfYear.ToString("000") + dt.ToString("HHmmss") + ran; 73 74 string checknum = Genchecknum(refnum); 75 refnum = refnum + checknum; 76 //插入非重的Refnum到Hashtable中去,确保同一秒种生成的RefNum不出现重复 77 if (!Hashtable[ID].Contains(refnum)) 78 { 79 isnotunique = false; 80 Hashtable[ID].Add(refnum); 81 } 82 //循环再获取新的Refnum 83 runnum++; 84 if (runnum > 50000) 85 { 86 dt = DateTime.Now; 87 ID = dt.ToString("yyyyMMddHHmmss"); 88 } 89 } while (isnotunique); 90 91 } 92 else 93 { 94 Hashtable.Clear(); 95 string ran = random.Next(99999).ToString("00000"); 96 refnum = prefix + acctnum + dt.Year.ToString().Substring(3, 1) + dt.DayOfYear.ToString("000") + dt.ToString("HHmmss") + ran; 97 98 string checknum = Genchecknum(refnum); 99 refnum = refnum + checknum; 100 HashSet<string> hs = new HashSet<string>(); 101 hs.Add(refnum); 102 Hashtable.Add(ID, hs); 103 } 104 } 105 return refnum; 106 } 107 }