컴파일러 오류 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();
}
}
}
참고 항목
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기