protected(C# 参考)protected (C# Reference)

protected 关键字是一个成员访问修饰符。The protected keyword is a member access modifier.

本页涵盖 protected 访问。This page covers protected access. protected 关键字也属于 protected internalprivate protected 访问修饰符。The protected keyword is also part of the protected internal and private protected access modifiers.

受保护成员在其所在的类中可由派生类实例访问。A protected member is accessible within its class and by derived class instances.

有关 protected 和其他访问修饰符的比较,请参阅可访问性级别For a comparison of protected with the other access modifiers, see Accessibility Levels.

示例Example

只有在通过派生类类型进行访问时,基类的受保护成员在派生类中才是可访问的。A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type. 以下面的代码段为例:For example, consider the following code segment:

class A
{
    protected int x = 123;
}

class B : A
{
    static void Main()
    {
        var a = new A();
        var b = new B();

        // Error CS1540, because x can only be accessed by
        // classes derived from A.
        // a.x = 10; 

        // OK, because this class derives from A.
        b.x = 10;
    }
}

语句 a.x = 10 生成错误,因为它是在静态方法 Main 中生成的,而不是类 B 的实例。The statement a.x = 10 generates an error because it is made within the static method Main, and not an instance of class B.

无法保护结构成员,因为无法继承结构。Struct members cannot be protected because the struct cannot be inherited.

示例Example

在此示例中,DerivedPoint 类是从 Point 派生的。In this example, the class DerivedPoint is derived from Point. 因此,可以从派生类直接访问基类的受保护成员。Therefore, you can access the protected members of the base class directly from the derived class.

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 的访问级别更改为 private,编译器将发出错误消息:If you change the access levels of x and y to private, the compiler will issue the error messages:

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

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

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范中的声明的可访问性For more information, see Declared accessibility in the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also