컴파일러 오류 CS1540

'type1' 형식의 한정자를 통해 보호된 멤버 'member'에 액세스할 수 없습니다. 한정자는 'type2' 형식이거나 여기에서 파생된 형식이어야 합니다.

파생 클래스는 기본 클래스 인스턴스를 통해 기본 클래스의 보호된 멤버에 액세스할 수 없습니다. 파생 클래스에서 선언된 기본 클래스 인스턴스는 런타임에 동일한 기본 클래스에서 파생되었지만 파생 클래스와 달리 관련이 없는 다른 형식의 인스턴스일 수도 있습니다. 보호된 멤버는 파생 형식을 통해서만 액세스할 수 있기 때문에 런타임에 유효하지 않을 수 있는 보호된 멤버에 액세스하려는 모든 시도는 컴파일러에서 유효하지 않은 것으로 표시됩니다.

다음 예제의 Employee 클래스에서 emp2emp3은 컴파일 시간에 둘 다 Person 형식이지만 emp2는 런타임에 Manager 형식입니다. EmployeeManager에서 파생되지 않았기 때문에 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();  
  
        }  
    }  
}  

참고 항목