如果可以通过反射访问私有构造函数,那么它们还有什么意义呢?
也许还有私有静态方法和属性等。
and maybe private static method and properties, etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
也许还有私有静态方法和属性等。
and maybe private static method and properties, etc.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
访问修饰符有助于指导程序流程。它们就像交通信号 - 你不必遵守它们,在某些情况下,授权玩家可能会选择忽略它们,但你通常想要尊重它们,因为它们使一切运行得更加顺利。
Access modifiers help direct program flow. They are like traffic signals - you don't have to obey them, and in certain situations authorized players may choose to ignore them, but you usually want to respect them because they make everything run much more smoothly.
私有构造函数通常与设计模式一起使用(例如,工厂方法模式、单例模式 )以防止对象被错误实例化。
如果不需要访问任何实例变量(编译器不必检查对象是否为非空等),则调用私有静态方法通常会更快。
Private constructors are often used with design patterns (eg. Factory Method Pattern, Singleton Pattern ) to prevent objects being incorrectly instantiated.
Private static methods are often faster to call if you don't need to access any instance variables (the compiler doesn't have to check the object is non-null among other things).
反射被认为是一种比通常访问类更强大的方法 - 建议拒绝不受控制的代码的非公共访问 - 请参阅 ReflectionPermission。
换句话说,人们只有在您允许的情况下才能访问您的类内部 - 与首先设置访问修饰符相同,对于具有程序集引用的直接客户端。任何成员只有在您让它可见时才可见。
Reflection is recognized as a more powerful than usual way to access your classes - recommendations are that non-public access be denied for uncontrolled code - see ReflectionPermission.
In other words, people only access your class internals if you let them - just the same as with setting access modifiers in the first place, for direct clients with an assembly reference. Any member is only visible if you let it be visible.
这种行为在 Silverlight 运行时中有所不同,基本上反射只能执行编译器(C# 或 VB)允许执行的操作。
因此,在 Silverlight 中,您无法使用私有构造函数进行实例化,即使使用 Activator.CreateInstance 也是如此。
This behavior is different in the Silverlight runtime, where basically reflection can only do what the compiler (C# or VB) is allowed to.
So in Silverlight, you can not instantiate using a private constructor, even with Activator.CreateInstance.