C# 班级与公共班级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12392876/
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
Class vs. Public Class
提问by
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 classand class?
那么public class和class之间有什么区别?
采纳答案by driis
Without specifying publicthe class is implicitly 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类是隐式的internal。这意味着该类仅在同一程序集中可见。当您指定时public,该类在程序集外可见。
It is also allowed to specify the internalmodifier explicitly:
还允许internal显式指定修饰符:
internal class Foo {}
回答by Anton Gogolev
By default, all classes (and all types for that matter) are internal, so in order for them to be accessible from the outside (sans stuff like InternalsVisibleToAttribute) you have to make them publicexplicitly.
默认情况下,所有classes(以及与此相关的所有类型)都是internal,因此为了让它们可以从外部访问(没有像 之类的东西InternalsVisibleToAttribute),您必须public明确地制作它们。
回答by Jon Hanna
The former is equivalent to:
前者相当于:
namespace Library{
internal class File{
//code inside it
}
}
All visibilities default to the least visible possible - privatefor members of classes and structs (methods, properties, fields, nested classes and nested enums) and internalfor direct members of namespaces, because they can't be private.
所有可见性都默认为最不可见的 -private对于classes 和structs 的成员(方法、属性、字段、嵌套类和嵌套enums)以及 sinternal的直接成员namespace,因为它们不能是私有的。
internalmeans 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:
这有两个原因:
- You should be consciously making things use the least visibility possible anyway, to strengthen your encapsulation.
- If they defaulted to
publicyou could accidentally make something public that should be private or internal. 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.
- 无论如何,您应该有意识地使事物使用尽可能少的可见性,以加强您的封装。
- 如果他们默认,
public你可能会意外地公开一些应该是私有的或内部的。如果您不小心使某些内容不够可见,则会出现明显的编译错误并进行修复。如果您不小心使某些内容太明显,则会在代码中引入一个不会被标记为错误的缺陷,这将是以后要修复的重大更改。
It's often considered better style to be explicit with your access modifiers, to be clearer in the code, just what is going on.
通常认为使用访问修饰符更明确的风格更好,在代码中更清晰,就是正在发生的事情。

