简体   繁体   English

能够通过反射分配无效的Enum值

[英]Able to assign an invalid Enum value via reflection

I've just come across some strange behavior when setting an enum's value via reflection. 通过反射设置枚举值时,我刚刚遇到了一些奇怪的行为。 It seems like I'm able to set an invalid value for the enum: 看来我可以为枚举设置无效的值:

class EnumReflector
{
    public enum MyEnum
    {
        Option1 = 0,
        Option2,
        Option3
    }

    public MyEnum TheEnum { get; set; }

    public void Test()
    {
        PropertyInfo pi = this.GetType().GetProperty("TheEnum");
        string badValue = "1234";
        object propertyValue = Enum.Parse(pi.PropertyType, badValue, true);

        pi.SetValue(this, propertyValue, null);
    }
}

Now, if I call this: 现在,如果我这样称呼:

        EnumReflector e = new EnumReflector();
        e.Test();
        if (e.TheEnum == EnumReflector.MyEnum.Option1 ||
            e.TheEnum == EnumReflector.MyEnum.Option2 ||
            e.TheEnum == EnumReflector.MyEnum.Option3)
        {
            Console.WriteLine("Value is valid");
        }
        else
        {
            Console.WriteLine("Value is invalid: {0} ({1})", e.TheEnum.ToString(), (int)e.TheEnum);
        }

The output is: 输出为:

Value is invalid: 1234 (1234) 值无效:1234(1234)

How can this be? 怎么会这样? I though one of the very natures of enums is their restricted value-set! 尽管枚举的本质之一是它们的限定值设置!

Enums are just integers (of any integer primitive type, which can be specified) with some defined named constants. 枚举只是具有定义的命名常量的整数(可以指定任何整数原始类型)。 There is no need for reflection to assign a value which has no named constant: 无需反射即可分配没有命名常量的值:

enum MyEnum {
    None, One, Two
}

MyEnum e = (MyEnum)100;

Compiles and works just fine. 编译并正常工作。 Note that this is also the reason for the Enum.IsDefined() static method, which checks if an enum value is a defined value. 请注意,这也是Enum.IsDefined()静态方法的原因,该方法检查枚举值是否为已定义的值。

Enums are really stricted value-set, but at the compile time. 枚举确实是严格的值集,但是在编译时。 Here is the disadvantage of the reflection: you loose all the compile-time checks, provided by the compiler and operate the values for own responsibility. 这是反映的缺点:松开由编译器提供的所有编译时检查,并对值负责。

You don't even need to resort to reflection: 您甚至不需要求助于反思:

EnumReflector e = new EnumReflector();

e.TheEnum = (EnumReflector.MyEnum)1234;

if (e.TheEnum == EnumReflector.MyEnum.Option1 ||
    e.TheEnum == EnumReflector.MyEnum.Option2 ||
    e.TheEnum == EnumReflector.MyEnum.Option3)
{
    Console.WriteLine("Value is valid");
}
else
{
    Console.WriteLine("Value is invalid: {0} ({1})",
                      e.TheEnum.ToString(), (int)e.TheEnum);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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