扩展方法为空​​的枚举 [英] Extension method for nullable enum

查看:240
本文介绍了扩展方法为空​​的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写为空的一个枚举的扩展方法的。照片 就像这个例子:

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?,你会得到一个 枚举

(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

这篇关于扩展方法为空​​的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆