开发者

Why can you read an attribute placed on a const using reflection in C#?

I am playing around with reflection and by accident I realized I could place a custom field attribute on 开发者_如何学编程a const class variable, then (using reflection) I read the class' fields, find the const with the attribute and perform actions. This is working fine.

I am curious as to why it works fine. Unless I mis-understood how consts work, I thought constants were "compiled out" and all references to that constant became the constant's actual value after compiling. If this is the case, why can reflection still see the const values?


All the references to a const are compiled away - not the const declaration itself. Any const declarations are emitted as part of the IL by the compiler.

Here's an example (notice that the IL retains the const field).

C#:

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


I thought constants were "compiled out" and all references to that constant became the constant's actual value after compiling. If this is the case

I would say that this is not the case. A const is still a fully-fledged member of its class. Consider a library that exposes a public const. There might not even be any references (within the library itself) to be 'compiled out'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜