แก้ไข

แชร์ผ่าน


private protected (C# Reference)

The private protected keyword combination is a member access modifier. A private protected member is accessible by types derived from the containing class, but only within its containing assembly. For a comparison of private protected with the other access modifiers, see Accessibility Levels.

Note

The private protected access modifier is valid in C# version 7.2 and later.

Example

A private protected member of a base class is accessible from derived types in its containing assembly only if the static type of the variable is the derived class type. For example, consider the following code segment:

public class BaseClass
{
    private protected int myValue = 0;
}

public class DerivedClass1 : BaseClass
{
    void Access()
    {
        var baseObject = new BaseClass();

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

        // OK, accessed through the current derived class instance
        myValue = 5;
    }
}
// Assembly2.cs
// Compile with: /reference:Assembly1.dll
class DerivedClass2 : BaseClass
{
    void Access()
    {
        // Error CS0122, because myValue can only be
        // accessed by types in Assembly1
        // myValue = 10;
    }
}

This example contains two files, Assembly1.cs and Assembly2.cs. The first file contains a public base class, BaseClass, and a type derived from it, DerivedClass1. BaseClass owns a private protected member, myValue, which DerivedClass1 tries to access in two ways. The first attempt to access myValue through an instance of BaseClass will produce an error. However, the attempt to use it as an inherited member in DerivedClass1 will succeed.

In the second file, an attempt to access myValue as an inherited member of DerivedClass2 will produce an error, as it is only accessible by derived types in Assembly1.

If Assembly1.cs contains an InternalsVisibleToAttribute that names Assembly2, the derived class DerivedClass2 will have access to private protected members declared in BaseClass. InternalsVisibleTo makes private protected members visible to derived classes in other assemblies.

Struct members cannot be private protected because the struct cannot be inherited.

C# language specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also