为什么不C#有包私有? [英] Why doesn't C# have package private?

查看:127
本文介绍了为什么不C#有包私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习C#和从Java世界来了,我是一个有点困惑地看到,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.

为什么C#设计的这种方式?另外,我会怎么做类似如下:我有一个产品类和 ProductInstance 类。我希望有一个 ProductInstance 要创建的唯一方法是通过在产品类的工厂方法。在Java中,我会把 ProductInstance 在同一个包产品,但要其构造包专用,以便仅产品将有机会获得它。这样一来,谁想要创建一个 ProductInstance 只能通过在产品类工厂方法这样做。我将如何完成同样的事情在C#?

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#?

推荐答案

内部是你是什​​么之后。这意味着该成员是在同一程序集中的任何类访问。没有什么错将它用于此目的(产品和放大器; ProductInstance),并为它设计的事情之一。 C#选择不对命名空间显著 - 它们被用于组织,没有确定什么类型可以看到彼此,因为在Java中使用的包私有的。

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.

这篇关于为什么不C#有包私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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