protected (C# 參考)

更新:2007 年 11 月

protected 關鍵字是成員存取修飾詞。protected 成員可在其類別內由衍生類別執行個體存取。如需 protected 和其他存取修飾詞的比較,請參閱存取層級

範例

只有當存取是透過衍生類別型別進行時,才可以存取衍生類別中基底類別 (Base Class) 的 protected 成員。例如,請考量下列程式碼區段:

class A
{
    protected int x = 123;
}

class B : A
{
    static void Main()
    {
        A a = new A();
        B b = new B();

        // Error CS1540, because x can only be accessed by
        // classes derived from A.
        // a.x = 10; 

        // OK, because this class derives from A.
        b.x = 10;
    }
}

陳述式 a.x = 10 會產生錯誤,因為它位於靜態方法 Main,而不是類別 B 的執行個體。

結構成員不可以是 protected 成員是因為無法繼承結構。

在此範例中,類別 DerivedPoint 衍生自 Point。因此,您可以直接從該衍生類別存取基底類別的 protected 成員。

class Point 
{
    protected int x; 
    protected int y;
}

class DerivedPoint: Point 
{
    static void Main() 
    {
        DerivedPoint dpoint = new DerivedPoint();

        // Direct access to protected members:
        dpoint.x = 10;
        dpoint.y = 15;
        Console.WriteLine("x = {0}, y = {1}", dpoint.x, dpoint.y); 
    }
}
// Output: x = 10, y = 15

如果您將 x 和 y 的存取層級更改為 private,編譯器會發出錯誤訊息:

'Point.y' is inaccessible due to its protection level.

'Point.x' is inaccessible due to its protection level.

C# 語言規格

如需詳細資料,請參閱 C# 語言規格中的下列章節:

  • 3.5.1 宣告存取範圍

  • 3.5.3 執行個體成員的保護存取

  • 3.5.4 存取範圍條件約束

  • 10.3.5 存取修飾詞

請參閱

概念

C# 程式設計手冊

參考

C# 關鍵字

存取修飾詞 (C# 參考)

存取範圍層級 (C# 參考)

修飾詞 (C# 參考)

public (C# 參考)

private (C# 參考)

internal (C# 參考)

其他資源

C# 參考