protected (C# 參考)

protected 關鍵字是成員存取修飾詞。

注意

此頁面涵蓋 protected 存取。 protected 關鍵字也是屬於 protected internalprivate protected 存取修飾詞。

受保護的成員可在其類別內由衍生類別執行個體存取。

如需 protected 和其他存取修飾詞的比較,請參閱存取範圍層級

範例 1

只有在存取是透過衍生類別類型進行時,才可以存取衍生類別中屬於基底類別的受保護成員。 例如,請考慮下列程式碼區段:

class A
{
    protected int x = 123;
}

class B : A
{
    static void Main()
    {
        var a = new A();
        var 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 的執行個體中發出。

結構成員不可以是受保護的成員,因為無法繼承結構。

範例 2

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

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

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

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

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

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

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

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格已宣告存取範圍。 語言規格是 C# 語法及用法的限定來源。

另請參閱