【问题标题】:Create instance of unknown Enum with string value using reflection in C#在 C# 中使用反射创建具有字符串值的未知枚举实例
【发布时间】:2013-04-06 20:51:02
【问题描述】:

当我在运行时拥有枚举的 System.Type 并检查 BaseType 是否为 System.Enum 时,我无法确定如何准确地创建枚举实例,我的值是与项目匹配的 int 值在神秘的枚举中。

我目前的代码就是上面描述的逻辑,如下图。

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

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

(SomeEnumType)int

但由于我在代码时不知道 EnumType,我该如何实现相同的目标?

【问题讨论】:

  • 在“return ???”之后你想做什么有点令人困惑,为什么在这种情况下你需要反思。您仍然可以使用相同的 (SomeEnumType)type 将类型转换为 SomeEnumType。
  • 问题是我不知道哪个枚举是可能的,在运行时可能是任何.. 返回???类似于 [code] Enum.Parse(Type.GetType(type), ob);[/code]
  • 这一行Type.GetType(type).BaseType.ToString() == "System.Enum" 告诉我对象type 已经具有您的SomeEnumType 的类型,那么为什么需要将它从SomeEnumType 转换为SomeEnumType?您能否提供更多背景信息,说明您想通过此实现什么目标?
  • 是的,实际上这只是成功了,回答了我自己的问题.. 仅供参考,尽管我使用的是包含系统的一行数据。枚举的类型字符串和一个 int 形式的值使用该值创建所需的任何枚举的实例。不过感谢您的帮助:)

标签: c# reflection enums


【解决方案1】:

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

【讨论】:

  • 而不是enumType.BaseType == typeof(Enum),写enumType.IsEnum更容易(并且可能等效)。
  • 你为什么离开Enum.ToObject方法?我喜欢它,而不是像你现在那样通过 string 实例。
【解决方案2】:

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

【讨论】:

  • 这在几个方面似乎是错误的。 (1) 您的方法具有where 约束,但您忘记“定义”E 类型并使您的方法通用。 (2) 在调用方法时应该如何提供E?编译器不会推断它。 (3) 您的is 表达式在语法上是错误的。 is 的右侧是一个对象,而不是一个类型。也许您打算使用!= 而不是is?什么目的? (4) 返回类型要求你对非泛型Enum.Parse方法的输出进行强制转换。
  • 抱歉,输入时没有编译检查。已编辑以修复语法错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
  • 2017-12-06
  • 2017-12-05
相关资源
最近更新 更多