可以为空的枚举的扩展方法

我正在尝试为可为空的枚举编写一个Extension方法
与此示例一样:

// ItemType is an enum ItemType? item; ... item.GetDescription(); 

所以我写了这个方法,由于某些我不理解的原因而无法编译:

 public static string GetDescription(this Enum? theEnum) { if (theEnum == null) return string.Empty; return GetDescriptionAttribute(theEnum); } 

我在Enum?上收到以下错误Enum?

只有非可空值类型才能成为system.nullable的基础

为什么? 枚举不能为null

更新:

如果有很多枚举,则ItemType只是其中一个的示例。

System.Enum是一个class ,所以只需删除? 这应该工作。

(通过“这应该工作”,我的意思是如果你传入一个空值的ItemType? ,你将在方法中得到一个null Enum 。)

 public static string GetDescription(this Enum theEnum) { if (theEnum == null) return string.Empty; return GetDescriptionAttribute(theEnum); } enum Test { blah } Test? q = null; q.GetDescription(); // => theEnum parameter is null q = Test.blah; q.GetDescription(); // => theEnum parameter is Test.blah 

您应该在方法签名中使用实际的枚举类型:

 public static string GetDescription(this ItemType? theEnum) 

System.ValueTypeSystem.Enum不被视为值类型(仅从它们派生的类型),因此它们可以为空(并且您不要将它们指定为可为空)。 试试吧:

 // No errors! ValueType v = null; Enum e = null; 

你也可以尝试这个签名:

 public static string GetDescription(this T? theEnum) where T: struct 

这也允许struct s,这可能不是你想要的。 我想我记得有些库在编译后添加了enum的类型约束(C#不允许)。 只需要找到它……

编辑 :找到它:

http://code.google.com/p/unconstrained-melody/

您可以简单地使您的扩展方法通用:

 public static string GetDescription(this T? theEnum) where T : struct { if (!typeof(T).IsEnum) throw new Exception("Must be an enum."); if (theEnum == null) return string.Empty; return GetDescriptionAttribute(theEnum); } 

遗憾的是,您不能在通用约束中使用System.Enum ,因此扩展方法将显示所有可为空的值(因此额外检查)。

也许更好的是为你的枚举增加额外的价值并称之为空:)