我正在编写一个实用函数,它从数据库中获取一个整数并将一个类型化的枚举返回给应用程序。
这是我尝试做的事情(注意我在实际函数中传入了数据读取器和列名,而不是 int
):
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;
}
但它不会让我施放 (T)value
说:
Cannot convert type 'System.Enum' to 'T'.
此外,我还阅读了很多关于使用 Enum.IsDefined
的褒贬不一的评论。性能方面听起来很差。我还能如何保证有效值?
最佳答案
像这样:
return (T)(object)value;
关于c# - 我可以在 C# 中从泛型类型转换为枚举类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3260762/