C# 中的访问修饰符internal
和访问修饰符有什么区别?private
7 回答
internal is for assembly scope (i.e. only accessible from code in the same .exe or .dll)
private is for class scope (i.e. accessible only from code in the same class).
在下面找到解释。您可以查看此链接以获取更多详细信息 - http://www.dotnetbull.com/2013/10/public-protected-private-internal-access-modifier-in-c.html
私有: -私有成员只能在自己的类型(自己的类)中访问。
内部: - 内部成员只能在程序集中通过继承(其派生类型)或类实例访问。
参考 :
dotnetbull - c# 中的访问修饰符是什么
internal
members are visible to all code in the assembly they are declared in.
(And to other assemblies referenced using the [InternalsVisibleTo]
attribute)
private
members are visible only to the declaring class. (including nested classes)
An outer (non-nested) class cannot be declared private
, as there is no containing scope to make it private to.
To answer the question you forgot to ask, protected
members are like private
members, but are also visible in all classes that inherit the declaring type. (But only on an expression of at least the type of the current class)
Private members are accessible only within the body of the class or the struct in which they are declared.
Internal types or members are accessible only within files in the same assembly
private - 在类/范围/结构等中的封装。
internal - 封装在程序集中。
内部成员可在程序集中访问(仅在同一项目中可访问)
私有成员可以在同一个类中访问
初学者示例
解决方案中有 2 个项目(Project1、Project2),Project1 引用了 Project2。
- 用 Project2 编写的公共方法可以在 Project2 和 Project1 中访问
- 用 Project2 编写的内部方法只能在 Project2 中访问,而不能在 Project1 中访问
- 用 Project2 的 class1 编写的私有方法只能被同一个类访问。它既不能在项目 2 的其他类中访问,也不能在项目 1 中访问。
Internal 将允许您在多个业务逻辑类之间引用数据访问静态类(用于线程安全),而不是订阅它们以在连接池中继承该类/相互绊倒,并最终避免允许 DAL 类促进公共层面的访问。这在设计和最佳实践方面得到了无数支持。
实体框架很好地利用了这种类型的访问