c#唯一订单号生成代码

2021-05-12 13:28

阅读:526

标签:menu   get   line   order   pen   blog   write   log   ons   

技术分享技术分享
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;
            }
        }
        /// 
        /// 唯一订单号生成
        /// 
        /// 
        public static string GenerateOrderNumber()
        {
            string strDateTimeNumber = DateTime.Now.ToString("yyyyMMddHHmmssms");
            string strRandomResult = NextRandom(1000, 1).ToString();
            return strDateTimeNumber + strRandomResult;
        }
        /// 
        /// 参考:msdn上的RNGCryptoServiceProvider例子
        /// 
        /// 
        /// 
        /// 
        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 )
            {
                randomResult |= ((uint)randomNumber[i] 1 - i) * 8));
            }
            return (int)(randomResult % numSeeds) + 1;
        }
    }
}
View Code

 

c#唯一订单号生成代码

标签:menu   get   line   order   pen   blog   write   log   ons   

原文地址:http://www.cnblogs.com/kwm672225801/p/7572900.html


评论


亲,登录后才可以留言!