引用自此问题的答案。
Guid是值类型,因此类型为Guid的变量一开始就不能为null。
那么如果我看到这个呢?
public Nullable<System.Guid> SomeProperty { get; set; }
我应该如何检查这个是否为空?像这样吗?
(SomeProperty == null)
还是像这样吗?
(SomeProperty == Guid.Empty)
SomeProperty == null || SomeProperty == Guid.Empty
因为它可以是空的'Nullable',也可以是空的GUID,类似于这样{00000000-0000-0000-0000-000000000000}
Guid
,如果使用非可空变体,则 null
将序列化为 Guid.Empty
,这可以在此处节省一个 null
检查。 - zcoop98SomeProperty.HasValue 我认为这是你要找的。
可以看看 DevDave 或者 Sir l33tname 的回答。
编辑:顺便说一下,你可以写成 System.Guid?
而不是 Nullable<System.Guid>
;)
Guid?
而不是 Guid
。 - Don CheadleGuid
,HasValue
也会返回 true。
bool validGuid = SomeProperty.HasValue && SomeProperty != Guid.Empty;
Check Nullable<T>.HasValue
if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
//not valid GUID
}
else
{
//Valid GUID
}
public static class Validate
{
public static void HasValue(this Guid identity)
{
if (identity == null || identity == Guid.Empty)
throw new Exception("The GUID needs a value");
}
}
并使用扩展插件
public static void Test()
{
var newguid = Guid.NewGuid();
newguid.HasValue();
}
HasValue
属性:
SomeProperty.HasValue
例如:if (SomeProperty.HasValue)
{
// Do Something
}
else
{
// Do Something Else
}
FYI
public Nullable<System.Guid> SomeProperty { get; set; }
等同于:
public System.Guid? SomeProperty { get; set; }
MSDN 参考文档: http://msdn.microsoft.com/zh-cn/library/sksw8094.aspx
从C# 7.1开始,您可以使用默认字面量来生成类型的默认值,当编译器可以推断表达式类型时。
Console.Writeline(default(Guid));
// ouptut: 00000000-0000-0000-0000-000000000000
Console.WriteLine(default(int)); // output: 0
Console.WriteLine(default(object) is null); // output: True
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default
Nullable<Guid>
或Guid?
。 - Damien_The_UnbelieverGuid
是否为空,请参考:https://dev59.com/8mkw5IYBdhLWcg3whK08 - Don Cheadle