c#唯一订单号生成代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string uniqueNum = GenerateOrderNumber();
            Console.WriteLine("唯一码:{0}\t 长度为:{1}", uniqueNum, uniqueNum.Length);
            //测试是否会生成重复
            Console.WriteLine("时间+RNGCryptoServiceProvider()结合生成的唯一值,如下:");
            string _tempNum = string.Empty;
            for (int i = 0; i < 1000; i++)
            {
                string uNum = GenerateOrderNumber();
                Console.WriteLine(uNum);
                if (string.Equals(uNum, _tempNum))
                {
                    Console.WriteLine("上值存在重复,按Enter键继续");
                    Console.ReadKey();
                }
                //Sleep当前线程,是为了延时,从而不产生重复值。可以把它注释掉测试看
                Thread.Sleep(300);
                _tempNum = uNum;
            }
        }
        /// <summary>
        /// 唯一订单号生成
        /// </summary>
        /// <returns></returns>
        public static string GenerateOrderNumber()
        {
            string strDateTimeNumber = DateTime.Now.ToString("yyyyMMddHHmmssms");
            string strRandomResult = NextRandom(1000, 1).ToString();
            return strDateTimeNumber + strRandomResult;
        }
        /// <summary>
        /// 参考:msdn上的RNGCryptoServiceProvider例子
        /// </summary>
        /// <param name="numSeeds"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private static int NextRandom(int numSeeds, int length)
        {
            // Create a byte array to hold the random value.  
            byte[] randomNumber = new byte[length];
            // Create a new instance of the RNGCryptoServiceProvider.  
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            // Fill the array with a random value.  
            rng.GetBytes(randomNumber);
            // Convert the byte to an uint value to make the modulus operation easier.  
            uint randomResult = 0x0;
            for (int i = 0; i < length; i++)
            {
                randomResult |= ((uint)randomNumber[i] << ((length - 1 - i) * 8));
            }
            return (int)(randomResult % numSeeds) + 1;
        }
    }
}
View Code

 

posted @ 2017-09-22 08:45  守y1座_空城  阅读(1962)  评论(0编辑  收藏  举报