Why can reflection access protected/private member

2020-01-27 07:27发布

Why can reflection access protected/private member of class in C#?

Is this not safe for the class, why is reflection given such power? Is this an anti-pattern?

标签: c# reflection
3条回答
放荡不羁爱自由
2楼-- · 2020-01-27 08:00

Member accessibility is not a security feature. It is there to protect the programmer against himself or herself. It helps implementing encapsulation but it is by no means a security feature.

Reflection is tedious enough to use so that people normally don't go out of their way to use it to access non-public members. It's also quite slow. Reflection is normally used in special cases only. However, nothing can protect completely against human stupidity, if someone wants to abuse reflection he can easily do it, but even without the reflection API, they can achieve the same thing (if they're running in full trust, that is) if they are determined enough.

查看更多
Juvenile、少年°
3楼-- · 2020-01-27 08:12

This is necessary for scenarios such as remoting, serialization, materialization, etc. You shouldn't use it blindly, but note that these facilities have always been available in any system (essentially, by addressing the memory directly). Reflection simply formalises it, and places controls and checks in the way - which you aren't seeing because you are presumably running at "full trust", so you are already stronger than the system that is being protected.

If you try this in partial trust, you'll see much more control over the internal state.

Is it an anti-pattern?

Only if your code uses it inappropriately. For example, consider the following (valid for a WCF data-contract):

[DataMember]
private int foo;

public int Foo { get {return foo;} set {foo = value;} }

Is it incorrect for WCF to support this? I suspect not... there are multiple scenarios where you want to serialize something that isn't part of the public API, without having a separate DTO. Likewise, LINQ-to-SQL will materialize into private members if you so elect.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-01-27 08:17

Reflection is absolute necessary for a debugger. Imagine that you are stepping through your program and unable to see values of your private variables. That's probably the reason why reflection works in .NET and Java the way it works, to make debugging really easy.

If we wouldn't need debuggers, then I can imagine that reflection would be restricted more in the spirit of OOP.

查看更多
登录 后发表回答