Why can you read the attribute placed in const using reflection in C #?

I play with reflection, and by chance I realized that I can put my own field attribute in a class variable const, then (using reflection). I read the fields of the class, find the const with the attribute, and do the actions. This works fine.

I am curious why this is working fine. If I did not understand how constants work, I thought the constants were “compiled”, and all references to this constant became a constant actual value after compilation. If so, why are const values ​​still visible in the reflection?

+5
source share
2 answers

const , const. const IL.

( , IL const).

#

class Foo
{
    const int i = 0;
}

IL

.class private auto ansi beforefieldinit Foo
    extends [mscorlib]System.Object
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
    }


    .field private static literal int32 i = int32(0)    
}
+11

, "", . ,

, . A const - . , public const. ( ), "".

+1

All Articles