微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/93051.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐