protected 关键字是一个成员访问修饰符。受保护成员在它的类中可访问并且可由派生类访问。有关 protected 与其他访问修饰符的比较,请参见可访问性级别。
仅当访问通过派生类类型发生时,基类的受保护成员在派生类中才是可访问的。例如,请看以下代码段:
| 复制代码 |
---|
// protected_keyword.cs
using System;
class A
{
protected int x = 123;
}
class B : A
{
static void Main()
{
A a = new A();
B 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
将生成错误,因为 A 不是从 B 派生的。
结构成员无法受保护,因为无法继承结构。
示例
在此示例中,类 DerivedPoint
从 Point
派生;因此,可以从该派生类直接访问基类的受保护成员。
| 复制代码 |
---|
// protected_keyword_2.cs
using System;
class Point
{
protected int x; protected int y;
}
class DerivedPoint: Point
{
static void Main()
{
DerivedPoint dp = new DerivedPoint();
// Direct access to protected members:
dp.x = 10; dp.y = 15;
Console.WriteLine("x = {0}, y = {1}", dp.x, dp.y);
}
} |
输出
注释
如果将 x
和 y
的访问级别更改为 private,编译器将发出错误信息:
'Point.y' is inaccessible due to its protection level.
'Point.x' is inaccessible due to its protection level.
C# 语言规范
有关更多信息,请参见 C# 语言规范中的以下各章节:
-
3.5.1 声明的可访问性
-
3.5.3 对实例成员的受保护访问
-
3.5.4 可访问性约束
-
10.2.3 访问修饰符
请参见