通过创建对象,如何限制一个类不能被任何类使用? [英] How to restrict aclass not to be accessible for any class to consume, by creating it's object?

查看:75
本文介绍了通过创建对象,如何限制一个类不能被任何类使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我有关此Qsn的答案.

Please tell me answer for this Qsn.

推荐答案

如果您的意思是我如何停止从我的课程中衍生的课程?"然后将其声明为sealed
如果您不这样做,请进一步解释您的意思!
If you mean "How can I stop classes deriving from my class?" then declare it sealed
If you don''t, then please explain further what you do mean!


在该类中有一个私有构造函数.这样就无法实例化.另请参考单例模式
Have a private constructor in that class. So that it can''t be instantiated. Also refer singleton patterns


Albin是正确的.但是,我需要使这个答案更准确.

您应该确保该类的所有已定义构造函数都为private(如果没有访问修饰符,则为默认值),也就是说,它们都不应该为internalpublic.

如果绝对没有构造函数,则仍然可以实例化一个类,因为将提供隐式(隐藏)的无参数构造函数(仅当没有其他构造函数时).在这种情况下,如果显式提供了这种无参数的构造函数并将其私有化,则无法实例化该类;如果这是创建此类构造函数的唯一目的,则其主体可以为空. (感谢罗伯特·罗德(Robert Rohde)帮助我解决了该答案的第一版中的错误.很抱歉造成混淆.)

这为后门留下了可能:此类可能具有内部公共静态函数,该函数返回此类的实例.由于这种方法可以访问私有构造函数,因此这可能是创建实例的剩余方法.您决定如何处理这种可能性.

最后,即使没有成员是抽象的,也可以通过简单地将整个类声明为abstract来消除实例化的可能性.该类的唯一目的是充当基类.

—SA
Albin is right. However, I need to make this answer more accurate.

You should makes sure that all defined constructor''s of the class are private (which is the default if there is no access modifier), that is, none of them should be internal or public.

If there are absolutely no constructors, a class still can be instantiated, because an implicit (hidden) parameter-less constructor will be provided (only if there is no other constructors). In this case, if such parameter-less constructor is explicitly provided and private, the class cannot be instantiated; if this is the only purpose for creating such constructor, its body can be empty. (Thanks to Robert Rohde who helped me to fix my mistake in first version of this answer. Sorry for confusion.)

This leaves for the possibility of a back door: such class might have an internal public static function which returns an instance of this class. As such method has access to private constructors, this could be the remaining way to create an instance. You decide what to do with this possibility.

Finally, you can remove the possibility of instantiation by simply declaring the whole class as abstract, even in the case when not members are abstract. The only purpose of such class will be to serve as a base class.

—SA


这篇关于通过创建对象,如何限制一个类不能被任何类使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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