protected(C# 参考)

关键字 protected 是成员访问修饰符。

注释

本页涵盖 protected 访问。 protected关键字也是protected internalprivate protected访问修饰符的一部分。

受保护成员在其所在的类中可由派生类实例访问。

有关与其他访问修饰符的 protected 比较,请参阅 访问级别

示例 1

只有在通过派生类类型进行访问时,基类的受保护成员在派生类中才是可访问的。 例如,请考虑以下代码段:

namespace Example1
{
    class BaseClass
    {
        protected int myValue = 123;
    }

    class DerivedClass : BaseClass
    {
        static void Main()
        {
            var baseObject = new BaseClass();
            var derivedObject = new DerivedClass();

            // Error CS1540, because myValue can only be accessed through
            // the derived class type, not through the base class type.
            // baseObject.myValue = 10;

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

该语句 baseObject.myValue = 10 生成错误,因为它通过基类引用baseObject (类型 BaseClass)访问受保护的成员。 只能通过派生类类型或派生自它的类型访问受保护的成员。

private protected 不同,protected 访问修饰符允许从任何程序集中的派生类进行访问。 与 protected internal 不同,它 不允许 从同一程序集中的非派生类进行访问。

结构成员无法受到保护,因为无法继承结构。

示例 2

在此示例中,类 DerivedPoint 派生自 Point. 因此,可以直接从派生类访问基类的受保护成员。

namespace Example2
{
    class Point
    {
        protected int x;
        protected int y;
    }

    class DerivedPoint: Point
    {
        static void Main()
        {
            var dpoint = new DerivedPoint();

            // Direct access to protected members.
            dpoint.x = 10;
            dpoint.y = 15;
            Console.WriteLine($"x = {dpoint.x}, y = {dpoint.y}");
        }
    }
    // Output: x = 10, y = 15
}

如果将xy的访问级别更改为私有,编译器将发出错误消息:

'Point.y' is inaccessible due to its protection level.

'Point.x' is inaccessible due to its protection level.

跨程序集访问

以下示例演示了 protected 成员可从派生类访问,即使它们位于不同的程序集中也不例外:

// Assembly1.cs
// Compile with: /target:library
namespace Assembly1
{
    public class BaseClass
    {
        protected int myValue = 0;
    }
}
// Assembly2.cs
// Compile with: /reference:Assembly1.dll
namespace Assembly2
{
    using Assembly1;
    
    class DerivedClass : BaseClass
    {
        void Access()
        {
            // OK, because protected members are accessible from
            // derived classes in any assembly
            myValue = 10;
        }
    }
}

这种跨程序集可访问性是区分protectedprivate protected(限制对同一程序集的访问)的关键,但它与protected internal相似(尽管protected internal也允许从非派生类进行同一程序集的访问)。

C# 语言规范

有关详细信息,请参阅 C# 语言规范中的声明的可访问性。 语言规范是 C# 语法和用法的明确来源。

另请参阅