protected internal (C# リファレンス)

キーワード組み合わせ protected internal はメンバー アクセス修飾子です。 protected internal メンバーには、現在のアセンブリから、または包含クラスから派生した型からアクセスできます。 protected internal と他のアクセス修飾子の比較については、「アクセシビリティ レベル」を参照してください。

基底クラスのプロテクト内部メンバーは、包含アセンブリ内の任意の型からアクセスします。 派生クラス型の変数経由でアクセスする場合にのみ、別のアセンブリにある派生クラスでもアクセスできます。 たとえば、次のコード セグメントを考えてみます。

// Assembly1.cs
// Compile with: /target:library
public class BaseClass
{
   protected internal int myValue = 0;
}

class TestAccess
{
    void Access()
    {
        var baseObject = new BaseClass();
        baseObject.myValue = 5;
    }
}
// Assembly2.cs
// Compile with: /reference:Assembly1.dll
class DerivedClass : BaseClass
{
    static void Main()
    {
        var baseObject = new BaseClass();
        var derivedObject = new DerivedClass();

        // Error CS1540, because myValue can only be accessed by
        // classes derived from BaseClass.
        // baseObject.myValue = 10;

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

この例には、2 つのファイル (Assembly1.csAssembly2.cs) が含まれています。 最初のファイルには public 基底クラスである BaseClass ともう 1 つのクラスである TestAccess が含まれています。 BaseClass は protected internal メンバーの myValue を持っています。これは TestAccess 型にアクセスされます。 2 番目のファイルでは、BaseClass のインスタンス経由で myValue にアクセスしようとするとエラーが発生します。一方で、派生クラス DerivedClass のインスタンスからこのメンバーにアクセスすると成功します。

構造体は継承できないため、構造体メンバーは protected internal になりません。

protected internal メンバーのオーバーライド

virtual メンバーをオーバーライドする場合、オーバーライドされたメソッドのアクセシビリティ修飾子は、その派生クラスが定義されているアセンブリによって異なります。

派生クラスが基底クラスと同じアセンブリ内で定義されている場合、すべてのオーバーライドされたメンバーは protected internal アクセスとなります。 派生クラスが基底クラスとは異なるアセンブリ内で定義されている場合、オーバーライドされたメンバーは protected アクセスとなります。

// Assembly1.cs
// Compile with: /target:library
public class BaseClass
{
    protected internal virtual int GetExampleValue()
    {
        return 5;
    }
}

public class DerivedClassSameAssembly : BaseClass
{
    // Override to return a different example value, accessibility modifiers remain the same.
    protected internal override int GetExampleValue()
    {
        return 9;
    }
}
// Assembly2.cs
// Compile with: /reference:Assembly1.dll
class DerivedClassDifferentAssembly : BaseClass
{
    // Override to return a different example value, since this override
    // method is defined in another assembly, the accessibility modifiers
    // are only protected, instead of protected internal.
    protected override int GetExampleValue()
    {
        return 2;
    }
}

C# 言語仕様

詳細については、「C# 言語の仕様」を参照してください。 言語仕様は、C# の構文と使用法に関する信頼性のある情報源です。

関連項目