可访问性级别(C# 参考)Accessibility Levels (C# Reference)

使用访问修饰符 publicprotectedinternalprivate,为成员指定以下声明的可访问性级别之一。Use the access modifiers, public, protected, internal, or private, to specify one of the following declared accessibility levels for members.

声明的可访问性Declared accessibility 含义Meaning
public 访问不受限制。Access is not restricted.
protected 访问限于包含类或派生自包含类的类型。Access is limited to the containing class or types derived from the containing class.
internal 访问限于当前程序集。Access is limited to the current assembly.
protected internal 访问限于当前程序集或派生自包含类的类型。Access is limited to the current assembly or types derived from the containing class.
private 访问限于包含类。Access is limited to the containing type.
private protected 访问限于包含类或当前程序集中派生自包含类的类型。Access is limited to the containing class or types derived from the containing class within the current assembly. 自 C# 7.2 之后可用。Available since C# 7.2.

除使用 protected internalprivate protected 组合的情况外,一个成员或类型仅允许一个访问修饰符。Only one access modifier is allowed for a member or type, except when you use the protected internal or private protected combinations.

命名空间中不允许出现访问修饰符。Access modifiers are not allowed on namespaces. 命名空间没有任何访问限制。Namespaces have no access restrictions.

根据出现成员声明的上下文,仅允许某些声明的可访问性。Depending on the context in which a member declaration occurs, only certain declared accessibilities are permitted. 如果未在成员声明中指定访问修饰符,则将使用默认可访问性。If no access modifier is specified in a member declaration, a default accessibility is used.

未嵌套在其他类型中的顶级类型只能具有 internalpublic 可访问性。Top-level types, which are not nested in other types, can only have internal or public accessibility. 这些类型的默认可访问性为 internalThe default accessibility for these types is internal.

作为其他类型的成员的嵌套类型可以具有如下表所示的声明的可访问性。Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

成员Members of 默认成员可访问性Default member accessibility 允许的成员的声明的可访问性Allowed declared accessibility of the member
enum public None
class private public

protected

internal

private

protected internal

private protected
interface public None
struct private public

internal

private

嵌套类型的可访问性依赖于它的可访问域,该域是由已声明的成员可访问性和直接包含类型的可访问域这二者共同确定的。The accessibility of a nested type depends on its accessibility domain, which is determined by both the declared accessibility of the member and the accessibility domain of the immediately containing type. 但是,嵌套类型的可访问域不能超出包含类型的可访问域。However, the accessibility domain of a nested type cannot exceed that of the containing type.

C# 语言规范C# Language Specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also