为什么能反射访问保护在C#类/私有成员? [英] Why can reflection access protected/private member of class in C#?

查看:270
本文介绍了为什么能反射访问保护在C#类/私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么能反射访问受保护类/私有成员在C#?

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?

推荐答案

这是必要的情况下,如远程化,系列化,物化,等你不应该盲目地使用它,但要注意,这些设施具有的总是的任何系统是可利用(本质上来说,通过直接寻址的内存)。简单地反思其正式化,并把控制和检查的方式 - 你没有看到,因为你是presumably在完全信任运行,因此你已经比被保护的系统更强

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.

它是一个反模式?

只有当您的code使用它不当。例如,请考虑以下(有效期为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到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#类/私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆