加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:59:35 所属栏目:百科 来源:网络整理
导读:我试图为可空的枚举写一个扩展方法. 喜欢这个例子: // ItemType is an enumItemType? item;...item.GetDescription(); 所以我写了这个方法,由于某些我不明白的原因而不能编译: public static string GetDescription(this Enum? theEnum){ if (theEnum == n
我试图为可空的枚举写一个扩展方法.
喜欢这个例子:
// 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读