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

10

最近我在思考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一起使用效果不佳? - Thomas Ayoub
1
guid.ToByteArray() 返回一个包含此实例值的16个元素字节数组。 - Amit Kumar Ghosh
https://msdn.microsoft.com/en-us/library/system.guid.tobytearray(v=vs.110).aspx - Amit Kumar Ghosh
1
其中一半次序错误” - 错误取决于你认为正确的顺序。字节以不同的顺序打印 - 这更为真实。这会直接引发一个问题,可能的原因是什么?良好的术语是解决问题的一半。 - JensG
1个回答

11
根据微软的文档,返回的字节数组中字节的顺序与 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接