存取範圍層級 (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 NoneNone
class private public

protected

internal

private

protected internal

private protected
interface public NoneNone
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. 但是,巢狀型別的存取範圍領域不能超過包含型別 (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