简体   繁体   English

为什么C#没有包私有?

[英]Why doesn't C# have package private?

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". 我正在学习C#并来自Java世界,我有点困惑,看到C#没有“包私有”。 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. 我还看到了一些涉及internalpartial解决方法以及评论说这些变通方法违背了语言的设计。

Why was C# designed this way? 为什么C#这样设计? Also, how would I do something like the following: I have a Product class and a ProductInstance class. 另外,我将如何执行以下操作:我有一个Product类和一个ProductInstance类。 The only way I want a ProductInstance to be created is via a factory method in the Product class. 我想要创建ProductInstance的唯一方法是通过Product类中的工厂方法。 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. 在Java中,我将ProductInstance放在与Product相同的包中,但将其构造函数package private设为package private以便只有Product才能访问它。 This way, anyone who wants to create a ProductInstance can only do so via the factory method in the Product class. 这样,任何想要创建ProductInstance都只能通过Product类中的工厂方法执行此操作。 How would I accomplish the same thing in C#? 我如何在C#中完成同样的事情?

internal is what you are after. internal是你所追求的。 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. 将它用于此目的(Product&ProductInstance)没有任何问题,并且是它的设计之一。 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 . C#选择不使名称空间显着 - 它们用于组织,而不是确定哪些类型可以看到彼此,如在包含私有的 java中。

partial is nothing at all like internal or package private . partial就像internal 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. 它只是一种将类的实现拆分为多个文件的方法,并提供了一些可扩展性选项。

Packages don't really exist in the same way as they do in Java. 包实际上并不像在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. 使用internal来隐藏一个项目的成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM