Extension method for nullable enum

狂风中的少年 提交于 2019-12-10 02:06:34

问题


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);
}

I'm getting the following error on Enum?:

only non-nullable value type could be underlying of system.nullable

Why? Enum can not have the value null!

Update:

If have lots of enums, ItemType is just an example of one of them.


回答1:


System.Enum is a class, so just drop the ? and this should work.

(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



回答2:


You should use the actual enum type in your method signature:

public static string GetDescription(this ItemType? theEnum)

System.ValueType and System.Enum are not treated as value types (only types derived from them), so they are nullable (and you don't to specify them as nullable). Try it:

// No errors!
ValueType v = null;
Enum e = null;

You could also try this signature:

public static string GetDescription<T>(this T? theEnum) where T: struct

This also allows structs though, which might not be what you want. I think i remember some library that adds a type constraint of enum after compilation (C# doesn't allow it) though. Just need to find it...

EDIT: Found it:

http://code.google.com/p/unconstrained-melody/




回答3:


You can simply make your extension method generic:

public static string GetDescription<T>(this T? theEnum) where T : struct
{ 
    if (!typeof(T).IsEnum)
        throw new Exception("Must be an enum.");

    if (theEnum == null) 
        return string.Empty; 

    return GetDescriptionAttribute(theEnum); 
}

Unfortunately, you cannot use System.Enum in a generic constraint, so the extension method will show for all nullable values (hence the extra check).




回答4:


Maybe better is add extra value to your enum and call it null :)



来源:https://stackoverflow.com/questions/12956916/extension-method-for-nullable-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!