共用方式為


protected (C# 參照)

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

備註

此頁面涵蓋 protected 存取權。 關鍵詞protected也是protected internalprivate protected存取修飾詞的一部分。

受保護的成員可以透過其類別和衍生類別實例來存取。

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

範例 1

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

namespace Example1
{
    class BaseClass
    {
        protected int myValue = 123;
    }

    class DerivedClass : BaseClass
    {
        static void Main()
        {
            var baseObject = new BaseClass();
            var derivedObject = new DerivedClass();

            // Error CS1540, because myValue can only be accessed through
            // the derived class type, not through the base class type.
            // baseObject.myValue = 10;

            // OK, because this class derives from BaseClass.
            derivedObject.myValue = 10;
        }
    }
}

語句 baseObject.myValue = 10 會產生錯誤,因為它會透過基類參考存取受保護的成員(baseObject 屬於類型 BaseClass)。 受保護的成員只能透過衍生類別類型或衍生自它的型別來存取。

不同於 private protectedprotected 存取修飾詞允許從 任何元件中的衍生類別進行存取。 不同於 protected internal,它 不允許 從相同元件內的非衍生類別存取。

結構成員無法受到保護,因為無法繼承結構。

範例 2

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

namespace Example2
{
    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
}

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

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

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

跨元件存取

下列範例示範 protected 即使成員位於不同的元件中,也能從衍生類別存取:

// Assembly1.cs
// Compile with: /target:library
namespace Assembly1
{
    public class BaseClass
    {
        protected int myValue = 0;
    }
}
// Assembly2.cs
// Compile with: /reference:Assembly1.dll
namespace Assembly2
{
    using Assembly1;
    
    class DerivedClass : BaseClass
    {
        void Access()
        {
            // OK, because protected members are accessible from
            // derived classes in any assembly
            myValue = 10;
        }
    }
}

這種跨元件的存取性質是用來區分 protectedprivate protectedprivate protected 會限制存取至相同元件),但與 protected internal 類似(雖然 也允許非衍生類別存取相同元件)。

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格中的宣告輔助功能。 語言規格是 C# 語法和使用方式的最終來源。

另請參閱