简体   繁体   English

班级与公共班级

[英]Class vs. Public Class

What is the difference between: 有什么区别:

namespace Library{
    class File{
        //code inside it
   }
}

and: 和:

namespace Library{
   public class File{
       //code inside it
   }
}

So what will be the difference between public class and class ? 那么公共课班级之间的区别是什么?

Without specifying public the class is implicitly internal . 如果不指定public则该类隐式internal This means that the class is only visible inside the same assembly. 这意味着该类仅在同一个程序集中可见。 When you specify public , the class is visible outside the assembly. 指定public ,该类在程序集外部可见。

It is also allowed to specify the internal modifier explicitly: 它还允许显式指定internal修饰符:

internal class Foo {}

The former is equivalent to: 前者相当于:

namespace Library{
    internal class File{
        //code inside it
   }
}

All visibilities default to the least visible possible - private for members of class es and struct s (methods, properties, fields, nested classes and nested enum s) and internal for direct members of namespace s, because they can't be private. 所有能见度默认为最不可见的可能- private的成员class ES和struct S(方法,属性,字段,嵌套类和嵌套enum S)和internal进行的直接成员namespace S,因为他们不能是私有的。

internal means other code in the same assembly can see it, but nothing else (barring friend assemblies and the use of reflection). internal意味着同一个程序集中的其他代码可以看到它,但没有别的东西(禁止朋友程序集和使用反射)。

This makes sense for two reasons: 这有两个原因:

  1. You should be consciously making things use the least visibility possible anyway, to strengthen your encapsulation. 无论如何,你应该有意识地使用尽可能少的可见性,以加强你的封装。
  2. If they defaulted to public you could accidentally make something public that should be private or internal. 如果他们向public违约,你可能会意外地public一些私人或内部公开的东西。 If you accidentally make something not visible enough, you get an obvious compile error and fix it. 如果你不小心做了一些不够明显的东西,你会得到一个明显的编译错误并修复它。 If you accidentally make something too visible you introduce a flaw to your code that won't be flagged as an error, and which will be a breaking change to fix later. 如果你不小心把某些东西看得太可见,你就会在代码中引入一个不会被标记为错误的缺陷,这将是一个突破性的修改,以便以后修复。

It's often considered better style to be explicit with your access modifiers, to be clearer in the code, just what is going on. 通常认为使用访问修饰符明确更好的样式,在代码中更清楚,正是发生了什么。

默认情况下,所有class es(以及所有类型)都是internal ,因此为了能够从外部访问它们(没有像InternalsVisibleToAttribute这样的东西),你必须明确public它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM