C#函数:获取自定义GUID c#常用获取类型的方法有哪些?

C#函数:获取自定义GUID c#常用获取类型的方法有哪些?

编码文章call10242024-12-22 14:42:3220A+A-


代码如下:

       private readonly ThreadLocal<Random> random = new ThreadLocal<Random>(() => new Random());
       private void button1_Click(object sender, EventArgs e)
       {
           TryIt();
       }

       string GenerateGUID()
       {
           string currentDate = DateTime.Now.ToString("yyyyMMdd");
           string currentTime = DateTime.Now.ToString("HHmmss");
    
           string milliseconds = DateTime.Now.ToString("fff"); // 毫秒

           string GUID = currentDate + "-" + currentTime + "-" +
                         milliseconds + "-" + CreateRandomHex(3) + "-" +
                         CreateRandomHex(12);

           return GUID.ToUpper();
       }

       string CreateRandomHex(int length)
       {
           const string hexChars = "0123456789ABCDEF";
           StringBuilder hexString = new StringBuilder();
           using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
           {
               byte[] randomBytes = new byte[length];
               rng.GetBytes(randomBytes);

               for (int i = 0; i < length; i++)
               {
                   int index = randomBytes[i] % hexChars.Length;
                   hexString.Append(hexChars[index]);
               }
           }

           return hexString.ToString();
       }
       void TryIt()
       {
           for (int i = 0; i < 1000; i++)
           {
               string newGUID = GenerateGUID();
               Debug.WriteLine(newGUID);
           }
       }
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4