限制对象的创建 [英] Restrict object's creation

查看:91
本文介绍了限制对象的创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个很奇怪的问题。我有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.

这篇关于限制对象的创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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