用于仅在命名空间内公开类的 C# 访问修饰符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18467965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# access modifier for exposing class only within namespace
提问by Jaco
In java you have package level protection that ensures classes are only usable within the package.
在 Java 中,您具有包级保护,可确保类仅在包内可用。
Namespaces in C# act more or less like packages. But C# does not have a protection level for protecting classes within a namespace.
C# 中的命名空间或多或少类似于包。但是 C# 没有用于保护命名空间中的类的保护级别。
Is there a specific reason for this?
这有什么具体原因吗?
采纳答案by dasblinkenlight
There is no such access modifier: the closest modifier is internal
, but the unit of protection is the assembly in which the class resides, not its namespace.
没有这样的访问修饰符:最接近的修饰符是internal
,但保护单元是类所在的程序集,而不是它的命名空间。
One could argue that it is possible to achieve similar level of control using internal
, because both kinds of restriction keep outsiders from accessing the implementation details of your library. The only person to whom it makes a difference is you, the writer of the library, and you are in full control of what to expose and what to hide anyway. Essentially, it means that if you do not want to use a class outside its namespace, simply refrain from using it; if the class is internal
, nobody else will be able to use that class either.
有人可能会争辩说,使用 可以实现类似级别的控制internal
,因为这两种限制都会阻止外部人员访问您的库的实现细节。唯一对它有所影响的人是您,即图书馆的作者,您完全可以控制要公开什么和隐藏什么。本质上,这意味着如果您不想在其命名空间之外使用一个类,只需避免使用它;如果类是internal
,则其他人也无法使用该类。
回答by Alexandr Mihalciuc
In .NET there are assemlies(dll or exe files), you can use internal
modifier to limit access only within the same assembly
在 .NET 中有程序集(dll 或 exe 文件),您可以使用internal
修饰符来限制仅在同一程序集中的访问
回答by User
Is there a specific reason for this?
这有什么具体原因吗?
Mostly, it's because there are some key differences between packages and namespaces
To simplify what's already been said in the linked question and here: Namespaces in C# are mostly to help with organizing an assembly's contents, both internally and externally. Java packages have more in common with C# assemblies, and there is an access modifier in C# that restricts to the assembly level: internal.
为了简化链接问题和此处已经说过的内容:C# 中的命名空间主要用于帮助在内部和外部组织程序集的内容。Java 包与 C# 程序集有更多共同点,并且 C# 中有一个访问修饰符限制在程序集级别:internal。