问题描述
为什么反射可以访问C#中类的protected/private成员?
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?
推荐答案
这对于远程、序列化、物化等场景来说是必要的.你不应该盲目使用它,但要注意这些设施总是 在任何系统中都可用(本质上,通过直接寻址内存).反射只是将其形式化,并在其中设置控制和检查 - 您没有看到这些,因为您大概是在完全信任"下运行,因此您已经比受保护的系统更强大.
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.
这是一种反模式吗?
仅当您的代码使用不当.例如,考虑以下(对 WCF 数据契约有效):
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;} }
WCF 支持这个不正确吗?我怀疑不是......有多种场景,您希望序列化不属于公共 API 的内容,而无需单独的 DTO.同样,如果您愿意,LINQ-to-SQL 将具体化为私有成员.
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.
这篇关于为什么反射可以访问 C# 中类的受保护/私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!