共用方式為


受保護的內部(C# 參考)

關鍵詞 protected internal 組合是成員存取修飾詞。 你可以從目前的組裝體或從包含類別衍生的型別中存取受保護的內部成員。 如需與其他存取修飾詞的 protected internal 比較,請參閱 存取層級

C# 語言參考資料記錄了 C# 語言最新版本。 同時也包含即將推出語言版本公開預覽功能的初步文件。

文件中標示了語言最近三個版本或目前公開預覽版中首次引入的任何功能。

小提示

欲查詢某功能何時首次在 C# 中引入,請參閱 C# 語言版本歷史的條目。

包含組件中的任何型別都可以存取基底類別的受保護內部成員。 位於另一個組裝中的派生類別只有在透過該派生類別類型的變數時,才能存取該成員。 例如,請考慮下列程式代碼區段:

// 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 因為它們位於同一組裝體中。 在第二個檔案中,嘗試透過 的BaseClass實例存取myValue會產生錯誤,而透過派生類別的實例存取該成員則DerivedClass成功。 此存取規則顯示允許 protected internal 同一 組合內的任何類別任何組裝中的衍生類別存取,使其成為受保護存取修飾符中最寬鬆的。

struct 成員不能是 protected internal ,因為 struct 無法繼承。

覆寫受保護的內部成員

當你覆寫虛擬成員時,覆寫方法的可達性修飾符取決於你定義派生類別的組合語言。

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

另請參閱