生成唯一值的方法很多,下面就不同环境下生成的唯一标识方法一一介绍,作为工作中的一次总结,有兴趣的可以自行测试:

https://www.cnblogs.com/xinweichen/p/4287640.html

一、在 .NET 中生成

1、直接用.NET Framework 提供的 Guid() 函数,此种方法使用非常广泛。GUID(全局统一标识符)是指在一台机器上生成的数字,它保证对在同一时空中的任何两台计算机都不会生成重复的 GUID 值(即保证所有机器都是唯一的)。关于GUID的介绍在此不作具体熬述,想深入了解可以自行查阅MSDN。代码如下:

  1. 1 using System;
  2. 2 using System.Collections.Generic;
  3. 3 using System.Linq;
  4. 4 using System.Text;
  5. 5 namespace ConsoleApplication1
  6. 6 {
  7. 7 class Program
  8. 8 {
  9. 9 static void Main(string[] args)
  10. 10 {
  11. 11 string _guid = GetGuid();
  12. 12 Console.WriteLine("唯一码:{0}\t长度为:{1}\n去掉连接符:{2}", _guid, _guid.Length, _guid.Replace("-", ""));
  13. 13 string uniqueIdString = GuidTo16String();
  14. 14 Console.WriteLine("唯一码:{0}\t长度为:{1}", uniqueIdString, uniqueIdString.Length);
  15. 15 long uniqueIdLong = GuidToLongID();
  16. 16 Console.WriteLine("唯一码:{0}\t长度为:{1}", uniqueIdLong, uniqueIdLong.ToString().Length);
  17. 17 }
  18. 18 /// <summary>
  19. 19 /// 由连字符分隔的32位数字
  20. 20 /// </summary>
  21. 21 /// <returns></returns>
  22. 22 private static string GetGuid()
  23. 23 {
  24. 24 System.Guid guid = new Guid();
  25. 25 guid = Guid.NewGuid();
  26. 26 return guid.ToString();
  27. 27 }
  28. 28 /// <summary>
  29. 29 /// 根据GUID获取16位的唯一字符串
  30. 30 /// </summary>
  31. 31 /// <param name=\"guid\"></param>
  32. 32 /// <returns></returns>
  33. 33 public static string GuidTo16String()
  34. 34 {
  35. 35 long i = 1;
  36. 36 foreach (byte b in Guid.NewGuid().ToByteArray())
  37. 37 i *= ((int)b + 1);
  38. 38 return string.Format("{0:x}", i - DateTime.Now.Ticks);
  39. 39 }
  40. 40 /// <summary>
  41. 41 /// 根据GUID获取19位的唯一数字序列
  42. 42 /// </summary>
  43. 43 /// <returns></returns>
  44. 44 public static long GuidToLongID()
  45. 45 {
  46. 46 byte[] buffer = Guid.NewGuid().ToByteArray();
  47. 47 return BitConverter.ToInt64(buffer, 0);
  48. 48 }
  49. 49 }
  50. 50 }

2、用 DateTime.Now.ToString("yyyyMMddHHmmssms") 和 .NET Framework 提供的 RNGCryptoServiceProvider() 结合生成,代码如下:

  1. 1 using System;
  2. 2 using System.Collections.Generic;
  3. 3 using System.Linq;
  4. 4 using System.Text;
  5. 5 using System.Threading;
  6. 6 namespace ConsoleApplication1
  7. 7 {
  8. 8 class Program
  9. 9 {
  10. 10 static void Main(string[] args)
  11. 11 {
  12. 12 string uniqueNum = GenerateOrderNumber();
  13. 13 Console.WriteLine("唯一码:{0}\t 长度为:{1}", uniqueNum, uniqueNum.Length);
  14. 14 //测试是否会生成重复
  15. 15 Console.WriteLine("时间+RNGCryptoServiceProvider()结合生成的唯一值,如下:");
  16. 16 string _tempNum = string.Empty;
  17. 17 for (int i = 0; i < 1000; i++)
  18. 18 {
  19. 19 string uNum = GenerateOrderNumber();
  20. 20 Console.WriteLine(uNum);
  21. 21 if (string.Equals(uNum, _tempNum))
  22. 22 {
  23. 23 Console.WriteLine("上值存在重复,按Enter键继续");
  24. 24 Console.ReadKey();
  25. 25 }
  26. 26 //Sleep当前线程,是为了延时,从而不产生重复值。可以把它注释掉测试看
  27. 27 Thread.Sleep(300);
  28. 28 _tempNum = uNum;
  29. 29 }
  30. 30 }
  31. 31 /// <summary>
  32. 32 /// 唯一订单号生成
  33. 33 /// </summary>
  34. 34 /// <returns></returns>
  35. 35 public static string GenerateOrderNumber()
  36. 36 {
  37. 37 string strDateTimeNumber = DateTime.Now.ToString("yyyyMMddHHmmssms");
  38. 38 string strRandomResult = NextRandom(1000, 1).ToString();
  39. 39 return strDateTimeNumber + strRandomResult;
  40. 40 }
  41. 41 /// <summary>
  42. 42 /// 参考:msdn上的RNGCryptoServiceProvider例子
  43. 43 /// </summary>
  44. 44 /// <param name="numSeeds"></param>
  45. 45 /// <param name="length"></param>
  46. 46 /// <returns></returns>
  47. 47 private static int NextRandom(int numSeeds, int length)
  48. 48 {
  49. 49 // Create a byte array to hold the random value.
  50. 50 byte[] randomNumber = new byte[length];
  51. 51 // Create a new instance of the RNGCryptoServiceProvider.
  52. 52 System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
  53. 53 // Fill the array with a random value.
  54. 54 rng.GetBytes(randomNumber);
  55. 55 // Convert the byte to an uint value to make the modulus operation easier.
  56. 56 uint randomResult = 0x0;
  57. 57 for (int i = 0; i < length; i++)
  58. 58 {
  59. 59 randomResult |= ((uint)randomNumber[i] << ((length - 1 - i) * 8));
  60. 60 }
  61. 61 return (int)(randomResult % numSeeds) + 1;
  62. 62 }
  63. 63 }
  64. 64 }

3、用 [0-9A-Z] + Guid.NewGuid() 结合生成特定位数的唯一字符串,代码如下:

  1. 1 using System;
  2. 2 using System.Collections.Generic;
  3. 3 using System.Linq;
  4. 4 using System.Text;
  5. 5 namespace ConsoleApplication1
  6. 6 {
  7. 7 class Program
  8. 8 {
  9. 9 static void Main(string[] args)
  10. 10 {
  11. 11 string uniqueText = GenerateUniqueText(8);
  12. 12 Console.WriteLine("唯一码:{0}\t 长度为:{1}", uniqueText, uniqueText.Length);
  13. 13 //测试是否会生成重复
  14. 14 Console.WriteLine("由[0-9A-Z] + NewGuid() 结合生成的唯一值,如下:");
  15. 15 IList<string> list = new List<string>();
  16. 16 for (int i = 1; i <= 1000; i++)
  17. 17 {
  18. 18 string _uT = GenerateUniqueText(8);
  19. 19 Console.WriteLine("{0}\t{1}", list.Count, _uT);
  20. 20 if (list.Contains(_uT))
  21. 21 {
  22. 22 Console.WriteLine("{0}值存在重复", _uT);
  23. 23 Console.ReadKey();
  24. 24 }
  25. 25 list.Add(_uT);
  26. 26 //if (i % 200 == 0)
  27. 27 //{
  28. 28 //Console.WriteLine("没有重复,按Enter键往下看");
  29. 29 //Console.ReadKey();
  30. 30 //}
  31. 31 }
  32. 32 list.Clear();
  33. 33 }
  34. 34
  35. 35 /// <summary>
  36. 36 /// 生成特定位数的唯一字符串
  37. 37 /// </summary>
  38. 38 /// <param name="num">特定位数</param>
  39. 39 /// <returns></returns>
  40. 40 public static string GenerateUniqueText(int num)
  41. 41 {
  42. 42 string randomResult = string.Empty;
  43. 43 string readyStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  44. 44 char[] rtn = new char[num];
  45. 45 Guid gid = Guid.NewGuid();
  46. 46 var ba = gid.ToByteArray();
  47. 47 for (var i = 0; i < num; i++)
  48. 48 {
  49. 49 rtn[i] = readyStr[((ba[i] + ba[num + i]) % 35)];
  50. 50 }
  51. 51 foreach (char r in rtn)
  52. 52 {
  53. 53 randomResult += r;
  54. 54 }
  55. 55 return randomResult;
  56. 56 }
  57. 57 }
  58. 58 }

4、用单例模式实现,由[0-9a-z]组合生成的唯一值,此文不讨论单例模式的多种实现方式与性能问题,随便弄一种方式实现,代码如下:

Demo结构如图: 

Program.cs 程序:

  1. 1 using System;
  2. 2 using System.Collections.Generic;
  3. 3 using System.Linq;
  4. 4 using System.Text;
  5. 5 using System.Collections;
  6. 6 using System.Xml;
  7. 7 namespace ConsoleApplication4
  8. 8 {
  9. 9 class Program
  10. 10 {
  11. 11 static void Main(string[] args)
  12. 12 {
  13. 13 CreateID createID = CreateID.GetInstance();
  14. 14 //测试是否会生成重复
  15. 15 Console.WriteLine("单例模式实现,由[0-9a-z]组合生成的唯一值,如下:");
  16. 16 IList<string> list = new List<string>();
  17. 17 for (int i = 1; i <= 1000000000; i++)
  18. 18 {
  19. 19 string strUniqueNum = createID.CreateUniqueID();
  20. 20 Console.WriteLine("{0}\t{1}", list.Count, strUniqueNum);
  21. 21 if (list.Contains(strUniqueNum))
  22. 22 {
  23. 23 Console.WriteLine("{0}值存在重复", strUniqueNum);
  24. 24 Console.ReadKey();
  25. 25 }
  26. 26 list.Add(strUniqueNum);
  27. 27 if (i % 200 == 0)
  28. 28 {
  29. 29 Console.WriteLine("没有重复,按Enter键往下看");
  30. 30 Console.ReadKey();
  31. 31 }
  32. 32 }
  33. 33 list.Clear();
  34. 34 }
  35. 35 }
  36. 36 /// <summary>
  37. 37 /// 单例模式实现
  38. 38 /// 唯一值由[0-9a-z]组合而成,且生成的每个ID不能重复
  39. 39 /// </summary>
  40. 40 public class CreateID
  41. 41 {
  42. 42 private static CreateID _instance;
  43. 43 private static readonly object syncRoot = new object();
  44. 44 private EHashtable hashtable = new EHashtable();
  45. 45 private string _strXMLURL = string.Empty;
  46. 46 private CreateID()
  47. 47 {
  48. 48 hashtable.Add("0", "0");
  49. 49 hashtable.Add("1", "1");
  50. 50 hashtable.Add("2", "2");
  51. 51 hashtable.Add("3", "3");
  52. 52 hashtable.Add("4", "4");
  53. 53 hashtable.Add("5", "5");
  54. 54 hashtable.Add("6", "6");
  55. 55 hashtable.Add("7", "7");
  56. 56 hashtable.Add("8", "8");
  57. 57 hashtable.Add("9", "9");
  58. 58 hashtable.Add("10", "a");
  59. 59 hashtable.Add("11", "b");
  60. 60 hashtable.Add("12", "c");
  61. 61 hashtable.Add("13", "d");
  62. 62 hashtable.Add("14", "e");
  63. 63 hashtable.Add("15", "f");
  64. 64 hashtable.Add("16", "g");
  65. 65 hashtable.Add("17", "h");
  66. 66 hashtable.Add("18", "i");
  67. 67 hashtable.Add("19", "j");
  68. 68 hashtable.Add("20", "k");
  69. 69 hashtable.Add("21", "l");
  70. 70 hashtable.Add("22", "m");
  71. 71 hashtable.Add("23", "n");
  72. 72 hashtable.Add("24", "o");
  73. 73 hashtable.Add("25", "p");
  74. 74 hashtable.Add("26", "q");
  75. 75 hashtable.Add("27", "r");
  76. 76 hashtable.Add("28", "s");
  77. 77 hashtable.Add("29", "t");
  78. 78 hashtable.Add("30", "u");
  79. 79 hashtable.Add("31", "v");
  80. 80 hashtable.Add("32", "w");
  81. 81 hashtable.Add("33", "x");
  82. 82 hashtable.Add("34", "y");
  83. 83 hashtable.Add("35", "z");
  84. 84 _strXMLURL = System.IO.Path.GetFullPath(@"..\..\") + "XMLs\\record.xml";
  85. 85
  86. 86 }
  87. 87 public static CreateID GetInstance()
  88. 88 {
  89. 89 if (_instance == null)
  90. 90 {
  91. 91 lock (syncRoot)
  92. 92 {
  93. 93 if (_instance == null)
  94. 94 {
  95. 95 _instance = new CreateID();
  96. 96 }
  97. 97 }
  98. 98 }
  99. 99 return _instance;
  100. 100 }
  101. 101 /// <summary>
  102. 102 /// 创建UniqueID
  103. 103 /// </summary>
  104. 104 /// <returns>UniqueID</returns>
  105. 105 public string CreateUniqueID()
  106. 106 {
  107. 107 long _uniqueid = GetGuidFromXml();
  108. 108 return Convert10To36(_uniqueid);
  109. 109 }
  110. 110 /// <summary>
  111. 111 /// 获取UniqueID总记录,即获取得到的这个ID是第几个ID
  112. 112 /// 更新UniqueID使用的个数,用于下次使用
  113. 113 /// </summary>
  114. 114 /// <returns></returns>
  115. 115 private long GetGuidFromXml()
  116. 116 {
  117. 117 long record = 0;
  118. 118 XmlDocument xmldoc = new XmlDocument();
  119. 119 xmldoc.Load(_strXMLURL);
  120. 120 XmlElement rootNode = xmldoc.DocumentElement;
  121. 121 //此次的个数值
  122. 122 record = Convert.ToInt64(rootNode["record"].InnerText);
  123. 123 //此次的个数值+1 == 下次的个数值
  124. 124 rootNode["record"].InnerText = Convert.ToString(record + 1);
  125. 125 xmldoc.Save(_strXMLURL);
  126. 126 return record;
  127. 127 }
  128. 128 /// <summary>
  129. 129 /// 10进制转36进制
  130. 130 /// </summary>
  131. 131 /// <param name="intNum10">10进制数</param>
  132. 132 /// <returns></returns>
  133. 133 private string Convert10To36(long intNum10)
  134. 134 {
  135. 135 string strNum36 = string.Empty;
  136. 136 long result = intNum10 / 36;
  137. 137 long remain = intNum10 % 36;
  138. 138 if (hashtable.ContainsKey(remain.ToString()))
  139. 139 strNum36 = hashtable[remain.ToString()].ToString() + strNum36;
  140. 140 intNum10 = result;
  141. 141 while (intNum10 / 36 != 0)
  142. 142 {
  143. 143 result = intNum10 / 36;
  144. 144 remain = intNum10 % 36;
  145. 145 if (hashtable.ContainsKey(remain.ToString()))
  146. 146 strNum36 = hashtable[remain.ToString()].ToString() + strNum36;
  147. 147 intNum10 = result;
  148. 148 }
  149. 149 if (intNum10 > 0 && intNum10 < 36)
  150. 150 {
  151. 151 if (hashtable.ContainsKey(intNum10.ToString()))
  152. 152 strNum36 = hashtable[intNum10.ToString()].ToString() + strNum36;
  153. 153 }
  154. 154 return strNum36;
  155. 155 }
  156. 156 }
  157. 157 /// <summary>
  158. 158 /// Summary description for EHashTable
  159. 159 /// </summary>
  160. 160 public class EHashtable : Hashtable
  161. 161 {
  162. 162 private ArrayList list = new ArrayList();
  163. 163 public override void Add(object key, object value)
  164. 164 {
  165. 165 base.Add(key, value);
  166. 166 list.Add(key);
  167. 167 }
  168. 168 public override void Clear()
  169. 169 {
  170. 170 base.Clear();
  171. 171 list.Clear();
  172. 172 }
  173. 173 public override void Remove(object key)
  174. 174 {
  175. 175 base.Remove(key);
  176. 176 list.Remove(key);
  177. 177 }
  178. 178 public override ICollection Keys
  179. 179 {
  180. 180 get
  181. 181 {
  182. 182 return list;
  183. 183 }
  184. 184 }
  185. 185 }
  186. 186 }

XML:

  1. 1 <?xml version="1.0" encoding="utf-8"?>
  2. 2 <root>
  3. 3 <record id="record">1</record>
  4. 4 </root>

二、在JS中生成GUID,类似.NET中的 Guid.NewGuid(),代码如下:

  1. 1 function newGuid() { //方法一:
  2. 2 var guid = "";
  3. 3 var n = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  4. 4 for (var i = 1; i <= 8; i++) {
  5. 5 guid += n;
  6. 6 }
  7. 7 return guid;
  8. 8 }
  9. 9 function newGuid() { //方法二:
  10. 10 var guid = "";
  11. 11 for (var i = 1; i <= 32; i++) {
  12. 12 var n = Math.floor(Math.random() * 16.0).toString(16);
  13. 13 guid += n;
  14. 14 if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
  15. 15 guid += "-";
  16. 16 }
  17. 17 return guid;
  18. 18 }

三、在SQL存储过程生成GUID,代码如下:

  1. 1 -- =============================================
  2. 2 -- Author: JBen
  3. 3 -- Create date: 2012-06-05
  4. 4 -- Description: 生成唯一标识ID,公共存储过程,可设置在别的存储过程调用此存储过程传不同的前缀
  5. 5 -- =============================================
  6. 6 ALTER PROCEDURE [dbo].[pro_CreateGuid]
  7. 7 @Prefix NVARCHAR(10),
  8. 8 @outputV_guid NVARCHAR(40) OUTPUT
  9. 9 AS
  10. 10 BEGIN
  11. 11 -- SET NOCOUNT ON added to prevent extra result sets from
  12. 12 -- interfering with SELECT statements.
  13. 13 SET NOCOUNT ON;
  14. 14 -- Insert statements for procedure here
  15. 15 SET @outputV_guid = @Prefix + REPLACE(CAST(NEWID() AS VARCHAR(36)),'-','')
  16. 16 END
 
分类: .net,c#
标签: c#唯一值GUID方法汇总
 

C#生成唯一值的方法汇总的更多相关文章

  1. 转:C#生成唯一值的方法汇总

    这篇文章主要介绍了C#生成唯一值的方法汇总,有需要的朋友可以参考一下 生成唯一值的方法很多,下面就不同环境下生成的唯一标识方法一一介绍,作为工作中的一次总结,有兴趣的可以自行测试: 一.在 .NET ...

  2. 生成GUID唯一值的方法汇总(dotnet/javascript/sqlserver)

    一.在 .NET 中生成1.直接用.NET Framework 提供的 Guid() 函数,此种方法使用非常广泛.GUID(全局统一标识符)是指在一台机器上生成的数字,它保证对在同一时空中的任何两台计 ...

  3. JS 生成唯一值UUID

    md5加密new Date()生成的值可能不是唯一的,另一种生成唯一值的方式: getUID: function() { // 获取唯一值 return 'xxxxxxxx-xxxx-4xxx-yxx ...

  4. PHP生成唯一ID的方法

    PHP自带生成唯一id的函数:uniqid() 它是基于当前时间微秒数的 用法如下: echo uniqid(); //13位的字符串 echo uniqid("php_"); / ...

  5. Java中生成唯一标识符的方法(Day_48)

    有时候业务需要生成唯一标识符,但又不能依赖于数据库中自动递增的字段产生唯一ID,比如多表同一字段需要统一一个唯一ID,此时我们就需要用程序来生成一个唯一的全局ID. UUID UUID是指在一台机器上 ...

  6. Java中生成唯一标识符的方法

    有时候业务需要生成唯一标识符,但又不能依赖于数据库中自动递增的字段产生唯一ID,比如多表同一字段需要统一一个唯一ID,此时我们就需要用程序来生成一个唯一的全局ID. UUID UUID是指在一台机器上 ...

  7. PyTorch 常用方法总结1:生成随机数Tensor的方法汇总(标准分布、正态分布……)

    在使用PyTorch做实验时经常会用到生成随机数Tensor的方法,比如: torch.rand() torch.randn() torch.normal() torch.linespace() 在很 ...

  8. js生成唯一值的函数

    利用了js的闭包性质 var uniqueNumber = (( function(){ var value = 0; return function(){ return ++value; }; }) ...

  9. Python生成唯一id的方法

    1. uuid import uuid def create_uid(): return str(uuid.uuid1()) if __name__ == '__main__': print(type ...

随机推荐

  1. Spring Boot程序获取tomcat启动端口

    package com.geostar.geostack.git_branch_manager.config; import org.springframework.beans.factory.ann ...

  2. 爬虫之Scrapy框架介绍

    Scrapy介绍 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内 ...

  3. tomcat在windows及linux环境下安装

    下载tomcat 下载地址: https://tomcat.apache.org/download-90.cgi 7,8,9的版本都可以下,这里下载最新版本 注意:Binary是编译好的,可以直接使用 ...

  4. Tomcat 部署java web项目直接ip地址访问项目

    正常情况下,在访问在Tomcat中部署的项目是 http://localhost:8080/demo 方式 其中,IP,端口,项目名(Demo)都是必须的. 那么,怎么样才能通过 http://loc ...

  5. docker的基础命令

    详细命令参考http://www.runoob.com/docker/docker-command-manual.html

  6. Luogu P3731 [HAOI2017]新型城市化

    题目显然可以转化为求每一条边对二分图最大独立集的贡献,二分图最大独立集\(=\)点数\(-\)最大匹配数,我们就有了\(50pts\)做法. 正解的做法是在原图上跑\(Tarjan\),最开始我想复杂 ...

  7. Python并发编程之IO模型

    目录 IO模型介绍 阻塞IO(blocking IO) 非阻塞IO(non-blocking IO) IO多路复用 异步IO IO模型比较分析 selectors模块 一.IO模型介绍 Stevens ...

  8. <六>企业级开源仓库nexus3实战应用–使用nexus3配置yum私有仓库

    一两个星期之前,你如果在我跟前说起私服的事情,我大概会绕着你走,因为我对这个东西真的一窍不通.事实上也正如此,开发同学曾不止一次的跟我说公司的私服版本太旧了,许多新的依赖编译之后不会从远程仓库自动缓存 ...

  9. <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

    <%String path = request.getContextPath();String basePath = request.getScheme()+"://"+re ...

  10. [物理学与PDEs]第1章第9节 Darwin 模型 9.3 Darwin 模型

    1. $\Omega$ 中 ${\bf A}={\bf A}_T+{\bf A}_L$, 其中 $\Div{\bf A}_T=0$, $\rot{\bf A}_L={\bf 0}$. 若 $$\bex ...