我试图为可空的枚举写一个扩展方法.
喜欢这个例子:
喜欢这个例子:
- // 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上收到以下错误?
only non-nullable value type could be underlying of system.nullable
为什么?枚举值不能为null!
更新:
如果有很多枚举,ItemType只是其中之一的一个例子.
解决方法
System.Enum是一个类,所以只要放下?这应该是正常的.
(通过“这应该工作”,我的意思是如果你传递一个null值的ItemType?,你会得到一个空的枚举在方法中.)
- 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