14

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

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

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

过去使用枚举时,我总是在代码时知道我要解析哪个枚举,但在这种情况下,我很困惑,而且几乎没有运气以谷歌友好的方式表达我的问题......我通常会做类似的事情

(SomeEnumType)int

但由于我在代码时不知道 EnumType 我怎么能实现同样的事情?

4

2 回答 2

19

使用类ToObject上的方法Enum

var enumValue = Enum.ToObject(type, value);

或者像您提供的代码一样:

if (Type.GetType(type) != null)
{
    var enumType = Type.GetType(type);
    if (enumType.IsEnum)
    {
        return Enum.ToObject(enumType, value);
    }
}
于 2013-04-06T21:00:15.567 回答
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());
}
于 2013-04-06T21:01:48.657 回答