C#创建唯一的订单号, 考虑时间因素
主要是想把日期和其它因素考虑进来。
使用RNGCryptoServiceProvider类创建唯一的最多8位数字符串。
private static string GetUniqueKey() { int maxSize = 8; int minSize = 5; char[] chars = new char[62]; string a; a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; chars = a.ToCharArray(); int size = maxSize; byte[] data = new byte[1]; RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(data); size = maxSize; data = new byte[size]; crypto.GetNonZeroBytes(data); StringBuilder result = new StringBuilder(size); foreach (byte b in data) { result.Append(chars[b % (chars.Length - 1)]); } return result.ToString(); }
然后,
for(int i = 0; i < 10; i++) { string str = string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), GetUniqueKey()); Console.WriteLine(str); } Console.ReadKey();