Can I cast from a generic type to an enum in C#?
I'm writing an utility function that gets a integer from the database and returns a typed enum to the application.
开发者_运维百科Here is what I tried to do (note I pass in a data reader and column name instead of the int
in my real function):
public static T GetEnum<T>(int enumAsInt)
{
Type enumType = typeof(T);
Enum value = (Enum)Enum.ToObject(enumType, enumAsInt);
if (Enum.IsDefined(enumType, value) == false)
{
throw new NotSupportedException("Unable to convert value from database to the type: " + enumType.ToString());
}
return (T)value;
}
But it won't let me cast (T)value
saying:
Cannot convert type 'System.Enum' to 'T'.
Also I've read quite a bit of mixed reviews about using Enum.IsDefined
. Performance wise it sounds very poor. How else can I guarantee a valid value?
Like this:
return (T)(object)value;
Change this:
Enum value = (Enum)Enum.ToObject(enumType, enumAsInt);
to this:
T value = (T)Enum.ToObject(enumType, enumAsInt);
and remove the cast :)
For information, using the generic constraint Enum
is available from C# 7.3 and greater.
精彩评论