为什么可以在 C# 中使用反射读取放置在 const 上的属性?
我正在玩反射,偶然我意识到我可以在 const 类变量上放置一个自定义字段属性,然后(使用反射)我读取类的字段,找到带有该属性的 const 并执行操作。这工作正常。
我很好奇为什么它工作得很好。除非我误解了 const 的工作原理,否则我认为常量是“编译出来的”,并且对该常量的所有引用在编译后都成为该常量的实际值。如果是这样的话,为什么反射还能看到const值呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对
const
的所有引用都会被编译掉,而不是const
声明本身。任何const
声明都会由编译器作为 IL 的一部分发出。下面是一个示例(请注意,IL 保留了
const
字段)。C#:
IL:
All the references to a
const
are compiled away - not theconst
declaration itself. Anyconst
declarations are emitted as part of the IL by the compiler.Here's an example (notice that the IL retains the
const
field).C#:
IL:
我会说事实并非如此。
const
仍然是其类的成熟成员。考虑一个公开public const
的库。甚至可能没有任何引用(在库本身内)需要“编译”。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 apublic const
. There might not even be any references (within the library itself) to be 'compiled out'.