繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM