如何在 C# 中使用 Guid?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/904021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:26:58  来源:igfitidea点击:

How to use Guids in C#?

c#guid

提问by Ante

This Code:

此代码:

Something = new Guid() 

is returning:

正在返回:

00000000-0000-0000-0000-000000000000

00000000-0000-0000-0000-000000000000

all the time and I can't tell why? So, why?

一直,我不知道为什么?所以为什么?

采纳答案by Will Dean

You should use Guid.NewGuid()

你应该使用 Guid.NewGuid()

回答by Josh

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.

简单解释一下为什么需要调用 NewGuid 而不是使用默认构造函数......在 .NET 中,所有结构(值类型,如 int、decimal、Guid、DateTime 等)都必须有一个默认的无参数构造函数来初始化所有字段为其默认值。在 Guid 的情况下,组成 Guid 的字节都为零。他们没有为 Guid 制作特殊情况或将其设为类,而是使用 NewGuid 方法生成新的“随机”Guid。

回答by DOK

It's in System.Guid.

在里面 System.Guid.

To dynamically create a GUID in code:

要在代码中动态创建 GUID:

Guid messageId = System.Guid.NewGuid();

To see its value:

要查看它的值:

string x = messageId.ToString();

回答by Leo

 Guid g1 = Guid.NewGuid();

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

回答by Will Yu

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

something = new Guid()等于something = Guid.Empty.

Use Guid.NewGuid();instead

使用Guid.NewGuid();替代