C#中的默认访问修饰符 [英] Default access modifier in C#
问题描述
如果我要创建一个如下所示的新对象,则默认情况下它将具有哪个访问修饰符?
If I will create a new object like the following, which access modifier will it have by default?
Object objectA = new Object();
推荐答案
任何成员将始终拥有限制性最强的一个-因此在这种情况下, objectA
的可访问性为 private
。 (假设它是一个实例变量。由于它们没有任何访问规则,因此作为局部变量没有意义。)
Any member will always have the most restrictive one available - so in this case the accessibility of objectA
is private
. (Assuming it's an instance variable. It makes no sense as a local variable, as they don't have any access rules as such.)
所以这:
class Foo
{
Object objectA = new Object();
}
与此等效:
internal class Foo
{
private Object objectA = new Object();
}
默认为大多数私有意味着对于类型,可访问性取决于上下文。
The "default to most private" means that for types, the accessibility depends on the context. This:
class Outer
{
class Nested
{
}
}
与此等效:
internal class Outer
{
private class Nested
{
}
}
...,因为您不能拥有私人的非嵌套类。
... because you can't have a private non-nested class.
只有一个 地方,添加显式访问修饰符可以使某些内容变得比没有该属性时更加私密,并且位于属性声明中:
There's only one place where adding an explicit access modifier can make something more private than it is without, and that's in property declarations:
public string Name { get; set; } // Both public
public string Name { get; private set; } // public get, private set
这篇关于C#中的默认访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!