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

我试图为可空的枚举写一个扩展方法.
喜欢这个例子:
// 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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...