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.
2 回答
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. 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.
The access modifiers in C# are not a security mechanism. 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.