仅在命名空间内公开类的 C# 访问修饰符 [英] C# access modifier for exposing class only within namespace

查看:33
本文介绍了仅在命名空间内公开类的 C# 访问修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 java 中,您有包级别的保护,可确保类仅在包中可用.

In java you have package level protection that ensures classes are only usable within the package.

C# 中的命名空间或多或少类似于包.但是 C# 没有用于保护命名空间中的类的保护级别.

Namespaces in C# act more or less like packages. But C# does not have a protection level for protecting classes within a namespace.

这有什么具体原因吗?

推荐答案

没有这样的访问修饰符:最接近的修饰符是internal,但是保护单元是类所在的程序集,而不是它的命名空间.

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 可以实现类似级别的控制,因为这两种限制都可以防止外人访问您的库的实现细节.唯一对它有影响的人是你,图书馆的作者,你完全可以控制要公开什么,要隐藏什么.从本质上讲,这意味着如果您不想在其命名空间之外使用某个类,只需避免使用它即可;如果类是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.

这篇关于仅在命名空间内公开类的 C# 访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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