protected (C# リファレンス)

更新 : 2007 年 11 月

protected キーワードは、メンバ アクセス修飾子です。protected メンバには、そのクラス内で派生クラス インスタンスからアクセスできます。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 のインスタンスではないため、エラーが生成されます。

構造体のメンバは保護されませんが、これは構造体の継承ができないためです。

この例では、DerivedPoint クラスは Point の派生クラスです。このため、基本クラスのプロテクト メンバに、派生クラスから直接アクセスできます。

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# リファレンス