C# GUID ToString的使用总结

2022-07-24,

最近在看到小伙伴直接使用 guid.tostring 方法,我告诉他需要使用 guid.tostring(“n”) 的方式输出字符串 ,为什么需要使用 n 这个参数呢,因为默认的是参数 d 在输出的时候会出现连字符

guid 是 globally unique identifier 全局唯一标识符的缩写,是一种由算法生成的唯一标识,在 c# dotnet 里面的 guid 类是微软的uuid标准的实现。

guid.tostring 里面可以添加下面几个参数,“n”,“d”,“b”,“p”,“x” 等

如果直接使用 guid.tostring() 那么就是使用 “d” 这个参数,添加了这个参数之后的输出格式大概如下,也就是在字符串中添加连字符

00000000-0000-0000-0000-000000000000
536b4dd7-f3dd-4664-bd69-bc0859d710ab

如果使用 “n” 那么就是只有32位数字,没有连字符,这里的数字是 16 进制表示的,也就是说字符串有 a-f 这几个英文字符和 0-9 的数字

00000000000000000000000000000000
2329fcac4fd640f1bc221e254b14d621

在我的业务里面,没有连字符看起来比较好看,于是我就建议小伙伴使用 guid 的字符串输出的时候加上 n 这个参数

而在 guid 格式化输出里面,可以选的参数中的 b 和 p 这只是在使用括号包字符串,如以下代码

      system.console.writeline(guid.newguid().tostring("b"));
      {e34dead4-212d-442a-8f4c-e00107baec24}
system.console.writeline(guid.newguid().tostring("p"));
(ac10d607-2b39-448f-99b5-0a3205cc9ac1)

从代码可以看到 b 使用 { 括号包含内容 ,使用参数 p 将使用 ( 括号包含内容

在 guid 格式化中的最特殊的是 x 参数,他会存在 4 个数字,最后一个数字是 8 个数字组合的,如下面代码

  console.writeline(guid.newguid().tostring("x"));
 {0xd3f51d9d,0x31b3,0x45f6,{0x9b,0x7c,0x89,0x1d,0xa5,0x6a,0xa3,0x43}}

guid 转 int

一个 guid 需要 16 个 byte 也就是 4 个 int 才能组成,可以使用下面的方法转换

   public static int[] guid2int(guid value)
    {
      byte[] b = value.tobytearray();
      int bint = bitconverter.toint32(b, 0);
      var bint1 = bitconverter.toint32(b, 4);
      var bint2 = bitconverter.toint32(b, 8);
      var bint3 = bitconverter.toint32(b, 12);
      return new[] {bint, bint1, bint2, bint3};
    }

    public static guid int2guid(int value, int value1, int value2, int value3)
    {
      byte[] bytes = new byte[16];
      bitconverter.getbytes(value).copyto(bytes, 0);
      bitconverter.getbytes(value1).copyto(bytes, 4);
      bitconverter.getbytes(value2).copyto(bytes, 8);
      bitconverter.getbytes(value3).copyto(bytes, 12);
      return new guid(bytes);
    }

本文会经常更新,请阅读原文: https://blog.lindexi.com/post/c-guid-tostring.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

以上就是c# guid tostring的使用总结的详细内容,更多关于c# guid tostring的资料请关注其它相关文章!

《C# GUID ToString的使用总结.doc》

下载本文的Word格式文档,以方便收藏与打印。