限制对象的创建
我在这里有一个很奇怪的问题。我有Class A,Class B和ClassC。我想创建Class B的对象,它可以创建A的对象。但是如何限制Class C从创建Class A的对象。
I have a very strange question here. I have Class A, Class B and Class C. I want to create object of Class B which can create the object of A. But how to restrict Class C from creating object of Class A.
一种方法是在B类中定义A类,以便只有B类可以创建A类的实例,而C类不能访问A类。
One way is define Class A inside Class B, so that Only Class B can create the instance of Class A and Class C cannot access Class A.
但是,我认为嵌套是错误的方法。
But, I think nesting is a wrong way.
我们有什么方法可以限制对象的创建吗?是否可以使用属性和反射来帮助限制?
Do we have any way to restrict the object creation? Is it possible to use attribute and reflection to help to restrict? If possible is there a recommended way?
请分享您的想法。
您可以将A类和B类放在单个程序集中,并将A类的构造函数标记为内部。
You can place class A and B in a single assembly and mark the constructor of class A as internal.
这样,只有该程序集中的类才能创建A类的实例。
This way, only classes within that assembly can create instances of class A.