[英]Create instance of unknown Enum with string value using reflection in C#
我有一個問題是如何在運行時創建一個枚舉實例,我有枚舉的System.Type並檢查過BaseType是System.Enum,我的值是一個匹配神秘項目的int值枚舉。
到目前為止我的代碼只是上面描述的邏輯,如下所示。
if (Type.GetType(type) != null)
{
if (Type.GetType(type).BaseType.ToString() == "System.Enum")
{
return ???;
}
}
在過去使用Enums時,我總是在代碼時間知道我想要解析的枚舉,但在這種情況下我很困惑,並且以谷歌友好的方式表達我的問題......我通常會做類似的事情
(SomeEnumType)int
但由於我不知道代碼時的EnumType如何才能實現同樣的目的呢?
在Enum
類上使用ToObject
方法:
var enumValue = Enum.ToObject(type, value);
或者像您提供的代碼:
if (Type.GetType(type) != null)
{
var enumType = Type.GetType(type);
if (enumType.IsEnum)
{
return Enum.ToObject(enumType, value);
}
}
使用(ENUMName)Enum.Parse(typeof(ENUMName), integerValue.ToString())
作為通用函數(編輯以糾正語法錯誤)...
public static E GetEnumValue<E>(Type enumType, int value)
where E : struct
{
if (!(enumType.IsEnum)) throw new ArgumentException("Not an Enum");
if (typeof(E) != enumType)
throw new ArgumentException(
$"Type {enumType} is not an {typeof(E)}");
return (E)Enum.Parse(enumType, value.ToString());
}
舊錯版本:
public E GetEnumValue(Type enumType, int value) where E: struct
{
if(!(enumType.IsEnum)) throw ArgumentException("Not an Enum");
if (!(typeof(E) is enumType))
throw ArgumentException(string.format(
"Type {0} is not an {1}", enumType, typeof(E));
return Enum.Parse(enumType, value.ToString());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.