如何在 C # 中使用 Guids?

本守则:

Something = new Guid()

正在返回:

000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

我不知道为什么,为什么?

83419 次浏览

Just a quick explanation for why you need to call NewGuid as opposed to using the default constructor... In .NET all structures (value types like int, decimal, Guid, DateTime, etc) must have a default parameterless constructor that initializes all of the fields to their default value. In the case of Guid, the bytes that make up the Guid are all zero. Rather than making a special case for Guid or making it a class, they use the NewGuid method to generate a new "random" Guid.

It's in System.Guid.

To dynamically create a GUID in code:

Guid messageId = System.Guid.NewGuid();

To see its value:

string x = messageId.ToString();
 Guid g1 = Guid.NewGuid();


string s1;
s1 = g1.ToString();
Console.WriteLine("{0}",s1);
Console.ReadKey();

something = new Guid() equals something = Guid.Empty.

Use Guid.NewGuid(); instead