2017-02-02 2 views
3

Child 클래스가 초기화 될 때 SecondChild 클래스 DoSomething이 다시 호출되지 않는 이유가 명확하지 않습니다. SecondChild 클래스의 재정의 메서드가 두 번 호출되지 않는 이유는 무엇입니까?

class Child : Parent 
{ 
    private string foo; 

    public Child() 
    { 
     foo = "HELLO"; 
    } 
    protected override void DoSomething() 
    { 
     Console.WriteLine(foo.ToLower()); 
    } 
} 
class SecondChild : Parent 
{ 
    public SecondChild() 
    { 
     var c = new Child(); 
    } 

    protected override void DoSomething() 
    { 
     Console.WriteLine("In second Child"); 
    } 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     SecondChild c = new SecondChild(); 
     Console.ReadLine(); 
    } 
} 

내가 SecondChildDoSomething() 두 번 여기에 호출 될 것을 예상하고 있었다

class Parent 
{ 
    public Parent() 
    { 
     DoSomething(); 
    } 
    protected virtual void DoSomething() 
    { 
     Console.WriteLine("Parent Method"); 
    } 
} 

, 대신 Child 클래스 DoSomething()NullException을 줄 것이다 호출됩니다. 이것에 대한

class Parent 
{ 
    protected string foo; 
    public Parent() 
    { 
     foo = "Parent1"; 
     DoSomething(); 
     foo = "Parent2"; 
    } 
    protected virtual void DoSomething() 
    { 
     Console.WriteLine("Parent Method"); 
    } 
} 

class Child : Parent 
{ 

    public Child() 
    { 
     foo = "HELLO"; 
    } 
    protected override void DoSomething() 
    { 
     Console.WriteLine(foo.ToLower()); 
    } 
} 

class SecondChild : Parent 
{ 
    public SecondChild() 
    { 
     var c = new Child(); 
    } 

    protected override void DoSomething() 
    { 
     Console.WriteLine("In second Child"); 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     SecondChild c = new SecondChild(); 
     Console.ReadLine(); 
    } 
} 

출력 될 것입니다 :

상위 1

이유는 둘째 아이

+2

디버거를 사용하십시오. _one_'SecondChild' 인스턴스 만 생성하십시오. 이 생성자에서는'SecondChild'가 아닌''Child'_ 인스턴스를 생성합니다. 따라서'SecondChild.DoSomething()'을 두 번 호출해야하는 이유는 무엇입니까? –

+1

질문에 실제 예상 출력을 포함해야합니다. 또한 http://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor를 읽으십시오. 일부 내용을 설명 할 수도 있습니다. – grek40

+0

예상 결과 및 실제 출력을 추가하십시오. "다시 불렀다"는 것은 너무 퍼지다. –

답변

4

나는 당신의 정의를 약간 조정 한? 자신이 SecondChild 클래스의 인스턴스를 만들 때 호출되는)

new SecondChild() 
    -> SecondChild:base() 
     -> base.DoSomething() //virtual 
    -> SecondChild.DoSomething() 
    -> new Child() 
    -> Child:base() 
     -> base.DoSomething() //virtual 
    -> Child.DoSomething() 
0

잘 해봐요 (하지만 당신이 만들고 클래스 아동의 인스턴스를 할 때, 먼저는 부모 클래스의 생성자를 실행합니다 메서드 호출 순서를 봐 자식 클래스의 DoSomething 메서드는 정상적으로 호출되었지만 Child 클래스의 생성자가 아직 실행되지 않았기 때문에 foo 필드가 아직 실행되지 않았으므로 foo.ToLower()가 null 참조 예외를 throw합니다.

해봐요 두 번 하위 클래스의 일단 한번 SecondChild을 요구하지만, 자식 클래스 때문에 foo는의 예외를 던지고 것은

그래서 여기에 까다로운 부분 기본 생성자는 파생의 생성자 전에 실행 얻을 널지고 클래스

관련 문제