c# – 可扩展枚举的扩展方法

前端之家收集整理的这篇文章主要介绍了c# – 可扩展枚举的扩展方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图为可空的枚举写一个扩展方法.
喜欢这个例子:
  1. // ItemType is an enum
  2. ItemType? item;
  3. ...
  4.  
  5. item.GetDescription();

所以我写了这个方法,由于某些我不明白的原因而不能编译:

  1. public static string GetDescription(this Enum? theEnum)
  2. {
  3. if (theEnum == null)
  4. return string.Empty;
  5.  
  6. return GetDescriptionAttribute(theEnum);
  7. }

我在Enum上收到以下错误

only non-nullable value type could be underlying of system.nullable

为什么?枚举值不能为null!

更新:

如果有很多枚举,ItemType只是其中之一的一个例子.

解决方法

System.Enum是一个类,所以只要放下?这应该是正常的.

(通过“这应该工作”,我的意思是如果你传递一个null值的ItemType?,你会得到一个空的枚举在方法中.)

  1. public static string GetDescription(this Enum theEnum)
  2. {
  3. if (theEnum == null)
  4. return string.Empty;
  5. return GetDescriptionAttribute(theEnum);
  6. }
  7. enum Test { blah }
  8.  
  9. Test? q = null;
  10. q.GetDescription(); // => theEnum parameter is null
  11. q = Test.blah;
  12. q.GetDescription(); // => theEnum parameter is Test.blah

猜你在找的C#相关文章