C# 将类实例的创建限制在命名空间内
我有两个对象,RoomManager
和 Room
,会有多个 Room
和一个 RoomManager
。我希望 RoomManager 成为唯一允许创建 Room
对象的容器。所以我想知道是否有一种方法可以使 Room
构造函数(以及其余的 Room
方法/属性)只能由 RoomManager.我在想也许可以将它们移动到自己的命名空间并将
Room
设为私有或内部或其他。从 辅助功能级别(C# 参考) 我看到内部是但对于整个程序集,而不仅仅是命名空间。
I have two objects, RoomManager
and Room
, there will be several Room
s and one RoomManager
. I want the RoomManager
to be the only one allowed to create a Room
object. So I'm wondering if there is a way to make the Room
constructor (and the rest of the Room
methods/properties) only accessible to the RoomManager
. I was thinking maybe moving them to their own namespace and making Room
private or internal or something. From Accessibility Levels (C# Reference) I see that internal is for the entire assembly though, not just the namespace.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,C#(以及一般的 .NET)没有特定于命名空间的访问修饰符。
一个相当黑客的解决方案是让 Room 只有一个私有构造函数,并使 RoomManager 成为一个嵌套类(可能只是称为 Manager):
像这样使用它:
正如我所说,但这有点黑客。当然,您可以将 Room 和 RoomManager 放在它们自己的程序集中。
No, C# (and .NET in general) has no access modifiers which are specific to namespaces.
One fairly hack solution would be to make Room just have a private constructor, and make RoomManager a nested class (possibly just called Manager):
Use it like this:
As I say, that's a bit hacky though. You could put Room and RoomManager in their own assembly, of course.
你可以这样做:
如果 Room 的构造函数是私有的,那么如果你在 Room 类中声明工厂类,它仍然可以从 Room.Factory 访问。
You can do something like this:
If the constructor of Room is private, it will still be accessible from Room.Factory if you declare the factory class inside the Room class.
在 RoomManager 本身内部定义 Room 并将其构造函数设为私有可能会有所帮助。
编辑:
但我认为最好的解决方案是提取 Room 的抽象类,并将该类公开给客户端。
没有人可以创建抽象类的实例。
Defining the Room inside of RoomManager itself and making it's constructor private could be helpful.
EDIT :
But the best solution I think is that to extract an abstract class of the Room, and expose that class to clients.
No one can create an instance of the abstract class.
您应该实现“单例模式”。它仅创建对象一次,任何后续创建该类型对象的尝试实际上都会返回已创建的对象。
您应该创建类工厂来为
RoomManager
实现单例。反过来,Room
应该是RoomNamer
的私有类型。RoomNamer
管理器应该具有创建Room
的方法。但在这种情况下,您无法访问RoomManager
类之外的Room
属性。为了解决这个问题,我建议您创建IRoom
公共接口,该接口将授予对房间功能的访问权限。因此,您的create room
方法将返回IRoom
接口。You should implement 'Singleton pattern'. It creates object only once and any subsequent attemps to create object of that type will actually returns already created object.
You should create class factory which would implement singleton for
RoomManager
.Room
, in turn, should be private type ofRoomNamager
.RoomNamager
manager should have method forRoom
creation. But in this case you cannot accessRoom
properties outside ofRoomManager
class. To solve this problem I recomend you to createIRoom
public interface which would grant access to room functionality. So yourcreate room
method would returnIRoom
interface.