无法通过“type1”类型的限定符访问受保护的成员“member”;限定符必须是“type2”类型(或从该类型派生)
派生类无法通过基类的实例访问其基类的受保护成员。 在运行时,派生类中声明的基类的实例可能是另一类型的实例,而后者是由同一基类派生,但与派生类无关的类型。 由于受保护的成员仅可由派生类型访问,因此在运行时对受保护成员可能无效的任何访问尝试,都会被编译器标记为无效。
在以下示例中的 Employee 类中,在编译时 emp2 和 emp3 都具有类型 Person,但在运行时 emp2 具有类型 Manager。 由于 Employee 不是派生自 Manager,因此它不能通过 Manager 类的实例访问基类的受保护成员 Person。 编译器无法确定两个 Person 对象的运行时类型。 因此,来自 emp2 的调用和来自 emp3 的调用都会导致编译器错误 CS1540。
using System;
using System.Text;
namespace CS1540
{
class Program1
{
static void Main()
{
Employee.PreparePayroll();
}
}
class Person
{
protected virtual void CalculatePay()
{
Console.WriteLine("CalculatePay in Person class.");
}
}
class Manager : Person
{
protected override void CalculatePay()
{
Console.WriteLine("CalculatePay in Manager class.");
}
}
class Employee : Person
{
public static void PreparePayroll()
{
Employee emp1 = new Employee();
Person emp2 = new Manager();
Person emp3 = new Employee();
// The following line calls the method in the Employee base class,
// Person.
emp1.CalculatePay();
// The following lines cause compiler error CS1540. The compiler
// cannot determine at compile time what the run-time types of
// emp2 and emp3 will be.
//emp2.CalculatePay();
//emp3.CalculatePay();
}
}
}