为什么无参数 Guid 构造函数会生成空 GUID?

发布于 2024-07-11 04:11:53 字数 94 浏览 6 评论 0原文

为什么无参数 Guid 构造函数会生成一个空 GUID,而不是像 Guid.NewGuid() 那样默认生成一个 GUID?

空 Guid 有特殊用途吗?

Why does the parameterless Guid constructor generate an empty GUID rather than default to a generated one as with Guid.NewGuid()?

Is there a particular use for an empty Guid?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

轻许诺言 2024-07-18 04:11:53

为什么无参数 Guid 构造函数会生成一个空 GUID,而不是像 Guid.NewGuid() 那样默认生成一个 GUID?

简短的回答:因为语言/运行时不允许 Guid 类型的设计者定义默认构造函数。

“默认构造”结构的值为零不仅是惯例,而且您根本无法为结构定义默认构造函数。 当您说 new Guid() 时,运行时会为您提供一个新对象,其中所有字段都初始化为其默认值:http://msdn.microsoft.com/en-us/library/ah19swz4%28VS.71%29.aspx

可以在此处找到一些基本原理:< a href="https://web.archive.org/web/20131102220804/http://www.yoda.arachsys.com/csharp/faq/#struct.constructors" rel="nofollow noreferrer">https:// web.archive.org/web/20131102220804/http://www.yoda.arachsys.com/csharp/faq/#struct.constructors

Why does the parameterless Guid constructor generate an empty GUID rather than default to a generated one as with Guid.NewGuid()?

Short answer: Because the language/runtime didn't let the designer of the Guid type define a default constructor.

It's not only conventional that the value of a "default-constructed" struct is zero, you simply cannot define a default constructor for a struct. When you say new Guid() the runtime gives you a new object where all the fields are initialized to their default values: http://msdn.microsoft.com/en-us/library/ah19swz4%28VS.71%29.aspx

Some rationale can be found here: https://web.archive.org/web/20131102220804/http://www.yoda.arachsys.com/csharp/faq/#struct.constructors

看海 2024-07-18 04:11:53

此行为与 .Net 框架中的其余值类型一致。 当“更新”值类型时,将使用默认值。 这恰好是 Guid 的默认值,类似于 Int32 的默认值 0。

This behavior is consistent with the rest of the value types in the .Net framework. When "newing up" a value type, a default value is used. This just happens to be the default for Guid similar to Int32's default value of 0.

停滞 2024-07-18 04:11:53

空 guid 可用于表示缺少 Guid。 由于值类型不可为空(默认情况下,您可以使用可为空)。

例如,我经常使用 Guid 作为 Id 属性,因为它们真的很容易使用。 因此,查看对象是否已持久化(即获取其 Id 时)的一种方法是,我可以根据空 guid 检查 id 的值。

An empty guid is useful to represent the lack of a Guid. Since value types are not nullable (by default yes you can use nullable).

For example I use a Guid as Id properties a lot cause they are real easy to work with. So one way to see if an object has been persisted (Which is when it gets its Id), I can check the value of id against an empty guid.

窝囊感情。 2024-07-18 04:11:53

我认为结构体或内置类型的默认值为零是惯例。

I think it's conventional that the default value, of a struct or of a built-in type, is zero.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文