자식 클래스에서 기본 클래스를 직접 호출하여 파생 클래스에 대해 정의 된 확장 메서드를 호출 할 수없는 이유는 무엇입니까 (기본 클래스에서 컴파일 오류가 발생하지 않습니다. 확장 메서드의 정의를 포함한다). 대신 아이 Intance에서 직접 호출 할 때 컴파일 오류없이 확장 메서드를 호출 할 수 있습니다. 당신은 확장 메서드를 호출 할 때하위 클래스의 기본 클래스 확장 메서드 호출
using System;
using System.Reflection;
public class Program
{
public static void Main()
{
Child child = new Child();
child.TestMethod();
}
}
// Derived class
public class Mother
{
}
// Child class
public class Child : Mother
{
public Child() : base()
{
}
public void TestMethod()
{
this.ExtentionMethod(3);// Ok: no compile errors
base.ExtentionMethod(3);// Ko: Compilation error (line 27, col 8): 'Mother' does not contain a definition for 'ExtentionMethod'
}
}
public static class Extender
{
public static void ExtentionMethod(this Mother mother, int i)
{
Console.WriteLine($"Mother extention method {i}");
}
}
왜 '* base.ExtentionMethod (3)'를 호출할까요? 그것은 정확히 this.ExtentionMethod (3)과 동일합니다. 이것은 예제가 이미 작동하는 것처럼 보여줍니다. –
@BradleyUffner 내가 알기에 호기심에 의해 기본 클래스에서 호출하는 것이 불가능한 이유를 알고 싶습니다. –
그 행동을 원할 수있는 유일한 시간은 'Child '버전처럼,'public static void ExtentionMethod (이 자식 child, int i) {}'처럼, @DStanley가 준 응답 에서처럼, 호출하기 전에'this'를'Mother'에 캐스트 할 것입니다. –