C# 如何创建 Guid 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2344098/
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-07 01:38:07  来源:igfitidea点击:

C# how to create a Guid value?

c#guid

提问by 5YrsLaterDBA

One field of our struct is Guid type. How to generate a valid value for it?

我们结构的一个字段是 Guid 类型。如何为其生成有效值?

采纳答案by David

Guid id = Guid.NewGuid();

回答by Adam Driscoll

Guid.NewGuid()creates a new random guid.

Guid.NewGuid()创建一个新的随机 guid。

回答by Dana Holt

Guid.NewGuid()will create one

Guid.NewGuid()将创建一个

回答by Justin

There are two ways

有两种方式

var guid = Guid.NewGuid();

or

或者

var guid = Guid.NewGuid().ToString();

both use the Guid class, the first creates a Guid Object, the second a Guid string.

两者都使用 Guid 类,第一个创建一个 Guid 对象,第二个创建一个 Guid 字符串。

回答by Justin

var guid = new Guid();

Hey, its a 'valid', although not very useful, Guid.

嘿,它是一个“有效”的,虽然不是很有用,Guid。

(the guid is all zeros, if you don't know. Sometimes this is needed to indicate no guid, in cases where you don't want to use a nullable Guid)

(如果您不知道,guid 全为零。有时这需要指示没有 guid,在您不想使用可为空的 Guid 的情况下)

回答by siphab

System.Guid desiredGuid = System.Guid.NewGuid();

回答by reza.cse08

To makes an "empty" all-0 guid like 00000000-0000-0000-0000-000000000000.

制作一个“空的”全 0 guid 像00000000-0000-0000-0000-000000000000.

var makeAllZeroGuID = new System.Guid();

or

或者

var makeAllZeroGuID = System.Guid.Empty;

To makes an actual guid with a unique value, what you probably want.

制作具有独特价值的实际 guid,您可能想要什么。

var uniqueGuID = System.Guid.NewGuid(); 

回答by sammer

//Retrive your key ID on the bases of GUID 

declare @ID as uniqueidentifier

SET @ID=NEWID()
insert into Sector(Sector,CID)

Values ('Diry7',@ID)


select SECTORID from sector where CID=@ID

回答by Zeliax

If you want to create a "desired" Guid you can do

如果你想创建一个“想要的”Guid,你可以这样做

var tempGuid = Guid.Parse("<guidValue>");

where <guidValue>would be something like 1A3B944E-3632-467B-A53A-206305310BAE.

哪里<guidValue>会像1A3B944E-3632-467B-A53A-206305310BAE.

回答by SAliaMunch

If you are using this in the Reflection C#, you can get the guid from the property attribute as follows

如果你在反射 C# 中使用它,你可以从 property 属性中获取 guid,如下所示

var propertyAttributes= property.GetCustomAttributes();
foreach(var attribute in propertyAttributes)
{
  var myguid= Guid.Parse(attribute.Id.ToString());
}