为什么 C# 没有私有包?
我正在学习 C#,来自 Java 世界,看到 C# 没有“私有包”,我有点困惑。我见过的大多数评论都是“你做不到;语言不是这样设计的”。我还看到了一些涉及 internal
和 partial
的解决方法,以及表示这些解决方法违背语言设计的评论。
为什么C#要这样设计?另外,我将如何执行类似以下操作:我有一个 Product
类和一个 ProductInstance
类。我想要创建 ProductInstance
的唯一方法是通过 Product
类中的工厂方法。在 Java 中,我会将 ProductInstance
与 Product
放在同一个包中,但将其构造函数设为 package private
,以便只有 Product
code> 将有权访问它。这样,任何想要创建 ProductInstance
的人都只能通过 Product
类中的工厂方法来实现。我如何在 C# 中完成同样的事情?
I'm learning C# and coming from a Java world, I was a little confused to see that C# doesn't have a "package private". Most comments I've seen regarding this amount to "You cannot do it; the language wasn't designed this way". I also saw some workarounds that involve internal
and partial
along with comments that said these workarounds go against the language's design.
Why was C# designed this way? Also, how would I do something like the following: I have a Product
class and a ProductInstance
class. The only way I want a ProductInstance
to be created is via a factory method in the Product
class. In Java, I would put ProductInstance
in the same package as Product
, but make its constructor package private
so that only Product
would have access to it. This way, anyone who wants to create a ProductInstance
can only do so via the factory method in the Product
class. How would I accomplish the same thing in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
internal
就是您所追求的。这意味着同一程序集中的任何类都可以访问该成员。将其用于此目的(产品和产品实例)没有任何问题,并且是其设计的目的之一。 C# 选择不让命名空间变得重要——它们用于组织,而不是确定哪些类型可以互相看到,就像在 java 中使用 package private 一样。partial
与internal
或package private
完全不同。它只是一种将类的实现拆分为多个文件的方法,并添加了一些可扩展性选项以进行良好的衡量。internal
is what you are after. It means the member is accessible by any class in the same assembly. There is nothing wrong with using it for this purpose (Product & ProductInstance), and is one of the things for which it was designed. C# chose not to make namespaces significant -- they are used for organization, not to determine what types can see one another, as in java with package private.partial
is nothing at all likeinternal
orpackage private
. It is simply a way to split the implementation of a class into multiple files, with some extensibility options thrown in for good measure.包实际上并不像 Java 中那样存在。命名空间用于组织代码并防止命名冲突,但不用于访问控制。项目/程序集可用于访问控制,但您不能像使用包那样拥有嵌套的项目/程序集。
使用
internal
对另一个项目隐藏一个项目的成员。Packages don't really exist in the same way as they do in Java. Namespaces are used to organize code and prevent naming clashes, but not for access control. Projects/assemblies can be used for access control, but you can't have nested projects/assemblies like you can with packages.
Use
internal
to hide one project's members from another.