protected internal (C# 參考)protected internal (C# Reference)

protected internal 關鍵字組合是成員存取修飾詞。The protected internal keyword combination is a member access modifier. protected internal 成員可以從目前的組件或衍生自包含類別的類型存取。A protected internal member is accessible from the current assembly or from types that are derived from the containing class. 如需 protected internal 和其他存取修飾詞的比較,請參閱存取範圍層級For a comparison of protected internal with the other access modifiers, see Accessibility Levels.

範例Example

基底類別的 protected internal 成員可以從其包含組件內的任何類型存取。A protected internal member of a base class is accessible from any type within its containing assembly. 它也可以在位於另一個組件的衍生類別內存取,但只能是在透過衍生類別類型的變數進行存取之時。It is also accessible in a derived class located in another assembly only if the access occurs through a variable of the derived class type. 例如,請考慮下列程式碼區段:For example, consider the following code segment:

// 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.csThis example contains two files, Assembly1.cs and Assembly2.cs. 第一個檔案包含公用的基底類別 BaseClass,以及另一個類別 TestAccessThe first file contains a public base class, BaseClass, and another class, TestAccess. BaseClass 擁有 protected internal 成員 myValue,它是由 TestAccess 類型存取。BaseClass owns a protected internal member, myValue, which is accessed by the TestAccess type. 在第二個檔案中,嘗試透過 BaseClass 的執行個體存取 myValue 會產生錯誤,而透過衍生類別 DerivedClass 的執行個體存取這個成員時會成功。In the second file, an attempt to access myValue through an instance of BaseClass will produce an error, while an access to this member through an instance of a derived class, DerivedClass will succeed.

結構成員不可以是 protected internal,因為無法繼承結構。Struct members cannot be protected internal because the struct cannot be inherited.

C# 語言規格C# language specification

如需詳細資訊,請參閱c # 語言規格For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also