为什么无参数 Guid 构造函数会生成空 GUID?
为什么无参数 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简短的回答:因为语言/运行时不允许 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
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
此行为与 .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.
空 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.
我认为结构体或内置类型的默认值为零是惯例。
I think it's conventional that the default value, of a struct or of a built-in type, is zero.