为什么没有 Guid.IsNullOrEmpty()方法

这让我想知道为什么.NET 中的 Guid 没有 IsNullOrEmpty()方法(其中空表示所有的零)

在编写 REST API 时,我需要在 ASP.NET MVC 代码中的几个地方使用这种方法。

Or am I missing something because nobody on the Internet has asked for the same?

96293 次浏览

Guidvalue type,因此 Guid类型的变量不能以 null 开始。如果您想知道它是否与空 guid 相同,只需使用:

if (guid == Guid.Empty)

首先,Guid不能为空,你可以检查:

myGuid == default(Guid)

相当于:

myGuid == Guid.Empty

您可以为 Guid 创建一个扩展方法来添加 IsEmpty 功能:

public static class GuidEx
{
public static bool IsEmpty(this Guid guid)
{
return guid == Guid.Empty;
}
}


public class MyClass
{
public void Foo()
{
Guid g;
bool b;


b = g.IsEmpty(); // true


g = Guid.NewGuid();


b = g.IsEmpty; // false


b = Guid.Empty.IsEmpty(); // true
}
}

下面是一个可为空的 Guid 的简单扩展方法。

/// <summary>
/// Determines if a nullable Guid (Guid?) is null or Guid.Empty
/// </summary>
public static bool IsNullOrEmpty(this Guid? guid)
{
return (!guid.HasValue || guid.Value == Guid.Empty);
}

更新

如果您真的想在任何地方使用它,那么您可以为常规 Guid 编写另一个扩展方法。它永远不会是空的,所以有些人不会喜欢这个... ... 但它服务于您正在寻找的目的,而且您不必知道您是否与 Guid 一起工作?或 Guid (适合重构等)。

/// <summary>
/// Determines if Guid is Guid.Empty
/// </summary>
public static bool IsNullOrEmpty(this Guid guid)
{
return (guid == Guid.Empty);
}

现在您可以在所有情况下使用 someGuid.IsNullOrEmpty();,无论您使用的是 Guid 还是 Guid。

就像我说的,有些人会抱怨命名,因为 IsNullOrEmpty()暗示值可能为 null (当它不能的时候)。如果你真的想要,想出一个不同的扩展名,如 IsNothing()IsInsignificant()或其他什么:)

你知道我经常看到这样的陈述

Guid 是一个值类型,因此类型为 Guid 的变量不能为 null start with

但这不是真的。

Agreed you can not programmatic set a Guid to null, but when some SQL pulls in a UniqueIdentifier and maps it to a Guid, and if that value is null in the db, the value comes up as null in the C#.

正如其他人指出的那样,问题的前提并不完全存在。C # Guid不可为空。然而,Guid?是。检查 Guid?null还是 Guid.Empty的一个简单方法是检查 GetValueOrDefault()的结果是否是 Guid.Empty。例如:

Guid? id;


// some logic sets id


if (Guid.Empty.Equals(guid.GetValueOrDefault()))
{
// Do something
}

下面是可空结构类型的通用扩展类:

public static class NullableExtensions
{
public static bool IsNullOrDefault<T>(this T? self) where T : struct
{
return !self.HasValue || self.Value.Equals(default(T));
}
}