使用C#中的反射创建具有字符串值的未知Enum实例

时间:2013-04-06 20:51:02

标签: c# reflection enums

我有一个问题是如何在运行时创建一个枚举实例,我有枚举的System.Type并检查过BaseType是System.Enum,我的值是一个与项匹配的int值在神秘的Enum中。

我到目前为止的代码只是上面描述的逻辑,如下所示。

        if (Type.GetType(type) != null)
        {
            if (Type.GetType(type).BaseType.ToString() == "System.Enum")
            {
                return ???;
            }
        }

在过去使用Enums时,我总是在代码时间知道我想要解析的枚举,但是在这种情况下我很困惑,并且用谷歌友好的方式表达了我的问题...我通常会这样做

之类的东西
(SomeEnumType)int

但是因为我在代码时不知道EnumType,我怎样才能达到同样的目的呢?

2 个答案:

答案 0 :(得分:14)

使用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);
    }
}

答案 1 :(得分:1)

使用(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());
}