加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么这两个字符串不相等?

发布时间:2020-12-15 17:50:55 所属栏目:百科 来源:网络整理
导读:我最近在想GUID,这让我试试这个代码: Guid guid = Guid.NewGuid();Console.WriteLine(guid.ToString()); //prints 6d1dc8c8-cd83-45b2-915f-c759134b93aaConsole.WriteLine(BitConverter.ToString(guid.ToByteArray())); //prints C8-C8-1D-6D-83-CD-B2-45-
我最近在想GUID,这让我试试这个代码:
Guid guid = Guid.NewGuid();
Console.WriteLine(guid.ToString()); //prints 6d1dc8c8-cd83-45b2-915f-c759134b93aa
Console.WriteLine(BitConverter.ToString(guid.ToByteArray())); //prints C8-C8-1D-6D-83-CD-B2-45-91-5F-C7-59-13-4B-93-AA
bool same=guid.ToString()==BitConverter.ToString(guid.ToByteArray()); //false
Console.WriteLine(same);

您可以看到所有的字节都在那里,但是当我使用BitConverter.ToString时,它们中的一半是错误的.为什么是这样?

解决方法

根据Microsoft documentation:

Note that the order of bytes in the returned byte array is different from the string representation of a Guid value. The order of the beginning four-byte group and the next two two-byte groups is reversed,whereas the order of the last two-byte group and the closing six-byte group is the same. The example provides an illustration.

using System;

public class Example
{
   public static void Main()
   {
      Guid guid = Guid.NewGuid();
      Console.WriteLine("Guid: {0}",guid);
      Byte[] bytes = guid.ToByteArray();
      foreach (var byt in bytes)
         Console.Write("{0:X2} ",byt);

      Console.WriteLine();
      Guid guid2 = new Guid(bytes);
      Console.WriteLine("Guid: {0} (Same as First Guid: {1})",guid2,guid2.Equals(guid));
   }
}
// The example displays the following output:
//    Guid: 35918bc9-196d-40ea-9779-889d79b753f0
//    C9 8B 91 35 6D 19 EA 40 97 79 88 9D 79 B7 53 F0
//    Guid: 35918bc9-196d-40ea-9779-889d79b753f0 (Same as First Guid: True)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读