星空网 > 软件开发 > ASP.net

[c#美味] Guid ToString 格式知多少?

在日常编程中,Guid是比较常用的,最常见的使用就是如下所示:

string id = Guid.NewGuid().ToString();

这条语句会生成一个新的Guid并转成字符串,如下:

// 10244798-9a34-4245-b1ef-9143f9b1e68a

但是还有一些情况下,我们会有一些细节上的差异,如:

  • 前后有大括号{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
  • 中间没有连字符 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  • 前后是圆括号(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

遇到这种情况就比较麻烦了,最常见的一种就是自己把guid生成的字符串解析处理,比如加括号,或者把连字符用空字符替换掉等:

var str = guid.ToString();var id = "{" + str + "}";var id2 = str.Replace("-", "");var id3 = "(" + str + ")";

 

其实不用这么麻烦的,在ToString的时候,有一个重载的函数:

ToString(String)

通过传入格式化字符串,就可以输出这种类型的guid 字符串了。

示例如下:

var guid = Guid.NewGuid();// 10244798-9a34-4245-b1ef-9143f9b1e68aConsole.WriteLine(guid.ToString("D"));// 102447989a344245b1ef9143f9b1e68aConsole.WriteLine(guid.ToString("N"));// {10244798-9a34-4245-b1ef-9143f9b1e68a}Console.WriteLine(guid.ToString("B"));// (10244798-9a34-4245-b1ef-9143f9b1e68a)Console.WriteLine(guid.ToString("P"));

 

注意:这里的D,N,B,P是不区分大小写的,如果传入空字符串,则使用的默认的D类型,其它情况都会报异常。

在MSDN中查询到还有一种“X”类型,但是我在.NetFx 3.5下,使用时会弹出异常:

未处理的异常:  System.FormatException: 格式字符串只能是“D”、“d”、“N”、“n ”、“P”、“p”、“B”或“b”。
   在 System.Guid.ToString(String format, IFormatProvider provider)
该文章转发微博为: http://www.cnblogs.com/greenerycn/archive/2010/04/25/guid_tostring_format.html(原著)




原标题:[c#美味] Guid ToString 格式知多少?

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

越南到中国海运价格:https://www.goluckyvip.com/tag/104687.html
出口到越南物流:https://www.goluckyvip.com/tag/104688.html
到越南运输:https://www.goluckyvip.com/tag/104689.html
DHL:https://www.goluckyvip.com/tag/10469.html
运输到越南:https://www.goluckyvip.com/tag/104690.html
中国越南运输:https://www.goluckyvip.com/tag/104691.html
深圳玉龙公园簕杜鹃花海花期时间+门票+交通:https://www.vstour.cn/a/365174.html
出境旅游预订须知:https://www.vstour.cn/a/365175.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流