GetFields method to get enum values

拈花ヽ惹草 提交于 2020-08-27 10:57:27

问题


  1. I have noticed that when calling GetFields() on enum type, I'm getting an extra fields with type int32. where did it come from??
  2. When I call the other overload (GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) ), it returns the desired fields. is that means that the enum's fields are not Public ?

thanks


回答1:


Reflector IL Spy can explain this.

Take a look at a decompiled enum and you will see something that looks like this:

.class public auto ansi sealed ConsoleApplication1.Foo
    extends [mscorlib]System.Enum
{
    // Fields
    .field public specialname rtspecialname int32 value__
    .field public static literal valuetype ConsoleApplication1.Foo Bar = int32(0)
    .field public static literal valuetype ConsoleApplication1.Foo Baz = int32(1)

} // end of class ConsoleApplication1.Foo

i.e. the Foo enum is implemented as a sealed class that wraps an int32 called value__ - the extra field you are seeing.

Its worth noting that it also inherits from System.Enum which also has extra (static) fields.




回答2:


I suspect the field is the underlying value - after all, that value has to be stored somewhere. So an enum like this:

public enum Foo
{
    Bar = 0,
    Baz = 1;
}

is a bit like this:

public struct Foo
{
    public static readonly Bar = new Foo(0);
    public static readonly Baz = new Foo(1);

    private readonly int value;

    public Foo(int value)
    {
        this.value = value;
    }
}



回答3:


See "Assemblies and scoping" in the Common Language Infrastructure (CLI) standard, ECMA standard 335. I would provide a more specific location but the specifics seem to be subject to change. Go to Ecma International for the standard. See "CLS Rule 7" that says:

The underlying type of an enum shall be a built-in CLS integer type, the name of the field shall be "value__", and that field shall be marked RTSpecialName.

That is the field, correct? I don't thoroughly understand that but at least it tries to explain what it is. It is required by the standard.



来源:https://stackoverflow.com/questions/8149591/getfields-method-to-get-enum-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!