为什么 C# 没有私有包?

发布于 2024-10-16 22:01:27 字数 577 浏览 7 评论 0原文

我正在学习 C#,来自 Java 世界,看到 C# 没有“私有包”,我有点困惑。我见过的大多数评论都是“你做不到;语言不是这样设计的”。我还看到了一些涉及 internalpartial 的解决方法,以及表示这些解决方法违背语言设计的评论。

为什么C#要这样设计?另外,我将如何执行类似以下操作:我有一个 Product 类和一个 ProductInstance 类。我想要创建 ProductInstance 的唯一方法是通过 Product 类中的工厂方法。在 Java 中,我会将 ProductInstanceProduct 放在同一个包中,但将其构造函数设为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坏尐絯℡ 2024-10-23 22:01:27

internal 就是您所追求的。这意味着同一程序集中的任何类都可以访问该成员。将其用于此目的(产品和产品实例)没有任何问题,并且是其设计的目的之一。 C# 选择不让命名空间变得重要——它们用于组织,而不是确定哪些类型可以互相看到,就像在 java 中使用 package private 一样。

partialinternal 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 like internal or package 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.

浊酒尽余欢 2024-10-23 22:01:27

包实际上并不像 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文