开发者

A private class that can be passed anywhere as a parameter - is such a thing possible?

开发者 https://www.devze.com 2023-02-09 16:14 出处:网络
I want to define a class, ClassA, that can be passed as a parameter to any method or class in a project (global scope). However, I want to enforce a constraint which will insure that ClassA can only b

I want to define a class, ClassA, that can be passed as a parameter to any method or class in a project (global scope). However, I want to enforce a constraint which will insure that ClassA can only be instantiated within the scope of a single ClassB. In other words, I want the class to have private scope with respect to ClassA while still being able to pass that object as a parameter to methods and classes distributed throughout the project.

I开发者_Python百科s this possible?


You can make ClassA abstract, and make a concrete implementation private to ClassB (as a nested class).


You can make ClassA a public abstract class, with an internal constructor.

ClassB can then define a class that derives from this, and creates the "real" instance. This will prevent anybody outside of your assembly from generating types of ClassA.


If I'm understanding what you want to do here correctly.....

Make ClassB a nested class of ClassA and make the constructor for ClassA private.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号