问题
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 struct
s 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