问题
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#?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/4964887/why-doesnt-c-sharp-have-package-private