Compiler Error CS1540

无法通过类型“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();

        }
    }
}

请参阅

继承(C# 编程指南)

多态性(C# 编程指南)

访问修饰符(C# 编程指南)

抽象类、密封类及类成员(C# 编程指南)