编程语言
首页 > 编程语言> > c# – 为什么SecondChild类的重写方法没有被调用两次?

c# – 为什么SecondChild类的重写方法没有被调用两次?

作者:互联网

我不清楚为什么在Child类初始化时没有再次调用SecondChild类DoSomething.

class Parent
{
    public Parent()
    {
       DoSomething();
    }
    protected virtual  void DoSomething()
    {
        Console.WriteLine("Parent Method");
    }
}
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();
    }
}

我期待SecondChild的DoSomething()将在这里被调用两次,而是调用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();
    }
}

输出将是:

In second Child

parent1

原因?查看方法调用顺序:

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

标签:c,constructor,virtual-method
来源: https://codeday.me/bug/20190623/1266169.html