共用方式為


受保護的內部成員 (C# 參考資料)

關鍵詞 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;
    }
}

這個範例包含兩個檔案,分別是 Assembly1.csAssembly2.cs。 第一個檔案包含公用基類、 BaseClass和另一個類別 TestAccessBaseClass 擁有受保護的內部成員 , myValue此成員是由 TestAccess 類型存取,因為它們位於相同的元件中。 在第二個檔案中,嘗試透過的實例myValue存取BaseClass會產生錯誤,而透過衍生類別DerivedClass的實例存取這個成員將會成功。 這表示protected internal允許從相同元件中的任何類別任何元件中的衍生類別進行存取,使其成為受保護存取修飾詞中最寬鬆的一種。

結構的成員不能標記為 `protected internal`,因為結構無法被繼承。

覆寫受保護的內部成員

覆寫虛擬成員時,覆寫方法的存取修飾詞取決於定義衍生類別所在的組件。

在與基類相同的元件中定義衍生類別時,所有覆寫的成員都具有 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# 語法和使用方式的最終來源。

另請參閱