检查c#中Nullable Guid是否为空

时间:2013-07-17 07:49:59

标签: c# guid

引自this问题的回答。

  

Guid是一种值类型,因此Guid类型的变量不能为null   从...开始。

如果我看到这个怎么办?

public Nullable<System.Guid> SomeProperty { get; set; }

我该如何检查这是否为空?喜欢这个?

(SomeProperty == null)

还是喜欢这个?

(SomeProperty == Guid.Empty)

7 个答案:

答案 0 :(得分:39)

如果您想确定需要同时检查

SomeProperty == null || SomeProperty == Guid.Empty

因为它可以为null'Nullable',它可以是一个像这样的空GUID {00000000-0000-0000-0000-000000000000}

答案 1 :(得分:20)

SomeProperty.HasValue我认为这就是你要找的东西。

编辑:顺便说一下,你可以写System.Guid?而不是Nullable<System.Guid>;)

答案 2 :(得分:7)

请注意,对于空HasValueGuid将返回true。

bool validGuid = SomeProperty.HasValue && SomeProperty != Guid.Empty;

答案 3 :(得分:3)

检查Nullable<T>.HasValue

if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
 //not valid GUID
}
else
{
 //Valid GUID
}

答案 4 :(得分:2)

您应该使用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/en-us/library/sksw8094.aspx

答案 5 :(得分:2)

从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://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default

答案 6 :(得分:0)

您可以创建一个扩展方法来验证 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();
    }