检查C#中的Nullable Guid是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17694131/
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
Check if Nullable Guid is empty in c#
提问by Saturnix
Quoting from an answer from thisquestion.
引用thisquestion的答案。
Guid is a value type, so a variable of type Guid can't be null to start with.
Guid 是值类型,因此 Guid 类型的变量一开始不能为 null。
What then if I see this?
那如果我看到这个怎么办?
public Nullable<System.Guid> SomeProperty { get; set; }
how should I check if this is null? Like this?
我应该如何检查这是否为空?像这样?
(SomeProperty == null)
or like this?
或者像这样?
(SomeProperty == Guid.Empty)
采纳答案by dotixx
SomeProperty.HasValueI think it's what you're looking for.
SomeProperty.HasValue我认为这就是你要找的。
EDIT : btw, you can write System.Guid?
instead of Nullable<System.Guid>
;)
编辑:顺便说一句,你可以写System.Guid?
而不是Nullable<System.Guid>
;)
回答by Mr. Mr.
You should use the HasValue
property:
您应该使用该HasValue
属性:
SomeProperty.HasValue
SomeProperty.HasValue
For example:
例如:
if (SomeProperty.HasValue)
{
// Do Something
}
else
{
// Do Something Else
}
FYI
供参考
public Nullable<System.Guid> SomeProperty { get; set; }
is equivalent to:
相当于:
public System.Guid? SomeProperty { get; set; }
The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx
MSDN 参考:http: //msdn.microsoft.com/en-us/library/sksw8094.aspx
回答by Sir l33tname
If you want be sure you need to check both
如果你想确定你需要检查两者
SomeProperty == null || SomeProperty == Guid.Empty
Because it can be null 'Nullable' and it can be an empty GUID something like this {00000000-0000-0000-0000-000000000000}
因为它可以是 null 'Nullable' 并且它可以是一个空的 GUID,例如 {00000000-0000-0000-0000-000000000000}
回答by Sriram Sakthivel
Check Nullable<T>.HasValue
查看 Nullable<T>.HasValue
if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
//not valid GUID
}
else
{
//Valid GUID
}
回答by DevDave
Note that HasValue
will return true for an empty Guid
.
请注意,HasValue
对于空的Guid
.
bool validGuid = SomeProperty.HasValue && SomeProperty != Guid.Empty;
bool validGuid = SomeProperty.HasValue && SomeProperty != Guid.Empty;