GetFields Method to Get Enumeration Values

  • I noticed that when I call GetFields() for type enum, I get additional fields of type int32. where does it come from??
  • When I call another overload (GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) ) , it returns the required fields. Does this mean enumeration fields are not public?

thanks

+4
source share
2 answers

Reflector IL Spy can explain this.

Take a look at the decompiled enumeration and you will see something similar to 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 enumeration is implemented as a private class that wraps an int32 called value__ - the extra field you see.

It is worth noting that it also inherits from System.Enum , which also has additional (static) fields.

+5
source

I suspect the field is a base value. In the end, this value must be stored somewhere. So an enumeration like this:

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

looks 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; } } 
+2
source

Source: https://habr.com/ru/post/1381454/


All Articles