简体   繁体   English

使用带有私有setter的属性对SetValue进行反射

[英]Using reflection to SetValue on property with private setter

I ran into, what I thought was a bug is actually, a feature detailed in This post . 我遇到了,我认为实际上是个错误, 这是本帖子中详细介绍的功能。 Can anyone explain to me why this is allowed? 谁能向我解释为什么允许这样做? It seems like a legacy quirk/bug that became useful. 似乎是一个古老的怪癖/错误变得有用。

I'm not sure which part of that you think is a bug, but it has always been possible to access the internals of a class via reflection when you cannot do so at compile time. 我不确定您认为哪一部分是错误,但是在编译时无法进行反射时,始终可以通过反射来访问类的内部。 This is by design. 这是设计使然。 Numerous aspects of the CLR rely on reflection to access fields, such as serialization. CLR的许多方面都依赖于对访问字段的反射,例如序列化。 The compiled IL needs to be able to access all fields of all objects, or else you couldn't set private fields from within your class. 编译后的IL必须能够访问所有对象的所有字段,否则您将无法类中设置私有字段。

The access modifiers in C# are not a security mechanism. C#中的访问修饰符不是安全机制。 If you are relying on a field being private to prevent anyone from setting it from the outside, you're doing something wrong. 如果您依靠私有字段来阻止任何人从外部进行设置,那么您在做错什么。 They exist to clearly delineate which parts of your class are it's public contract (and thus, in theory, stable) from those parts that are implementation details (and thus can change without notice.) 它们的存在是为了从与实现细节相关的那些部分(因此可以随时更改,恕不另行通知)中清楚地区分出您的课程的哪些部分是公共合同(理论上是稳定的)。

If you choose to use reflection to change the internal state of an object, despite all indications that you should leave it alone, you are taking the stability of your application into your own hands, and you get what deserve. 如果您选择使用反射来更改对象的内部状态,尽管有种种迹象表明您应该不理会它,但您会将应用程序的稳定性掌握在自己手中,您将得到应有的回报。

Reflection is allowed only for Full Trust code, so the code already able to do anything (including directly poking in memory of the process). 只有完全信任代码才允许进行反射,因此该代码已经可以执行任何操作(包括直接戳入进程的内存)。 So having supported way of changing values even for private properties does not make code any less secure. 因此,即使使用私有属性也支持更改值的方法不会降低代码的安全性。 It makes reflection API consistent and allows useful scenarios especially for testing. 它使反射API保持一致,并允许使用一些有用的方案,尤其是用于测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM