扩展方法为空的枚举
我想写为空的一个枚举的扩展方法的。照片 就像这个例子:
I'm trying to write an Extension method for nullable Enums.
Like with this example:
// ItemType is an enum
ItemType? item;
...
item.GetDescription();
所以我写了这个方法,它不会编译由于某种原因,我不明白:
So I wrote this method which doesn't compile for some reason that I don't understand:
public static string GetDescription(this Enum? theEnum)
{
if (theEnum == null)
return string.Empty;
return GetDescriptionAttribute(theEnum);
}
我收到以下错误枚举
:
唯一的非空值类型可能是潜在的system.nullable
only non-nullable value type could be underlying of system.nullable
为什么呢?枚举不能有值空
!
Why? Enum can not have the value null
!
更新:
如果有很多枚举,的ItemType
是其中之一的只是一个例子。的
If have lots of enums, ItemType
is just an example of one of them.
System.Enum
是类
,所以刚落?
这应该工作。
System.Enum
is a class
, so just drop the ?
and this should work.
(以这应该工作,我的意思是,如果你传递了一个空值的ItemType?
,你会得到一个空
枚举$ C $的方法C>)
(By "this should work", I mean if you pass in a null-valued ItemType?
, you'll get a null
Enum
in the method.)
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