【问题标题】:Why are these two strings not equal?为什么这两个字符串不相等?
【发布时间】:2016-03-19 23:26:24
【问题描述】:

我最近在考虑 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 时,其中一半的顺序错误。这是为什么呢?

【问题讨论】:

  • 盲目猜测:BitConverter 和 ByteArray 不能很好地协同工作?
  • guid.ToByteArray() 返回一个包含此实例值的 16 元素字节数组。
  • "其中一半的顺序错误" - 错误取决于您认为正确的顺序。字节以 不同的 顺序打印 - 这更正确。这将直接导致一个问题,可能是什么原因?好的术语是解决问题的一半。

标签: c# guid


【解决方案1】:

根据微软documentation

请注意,返回的字节数组中的字节顺序与 Guid 值的字符串表示不同。开始的四字节组和接下来的两个二字节组的顺序颠倒,而最后的二字节组和结束的六字节组的顺序相同。该示例提供了一个说明。

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)

【讨论】:

    最近更新 更多