Extension method for nullable enum

浪子不回头ぞ 提交于 2019-12-05 01:35:10

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

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/

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).

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

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