下列代码的运行结果是()?
Base obj = new Sub(); 运行顺序为:进入Sub()类-运行Sub()构造函数-运行Base()构造函数-运行Sub()中override 重写Func()函数- 输出Sub.Func-继续运行Sub()构造函数-运行Sub()构造函数中的Func()函数-输出Sub.Func-运行obj.Func()-进入Sub()-运行Func()-输出Sub.Func() 如果Sub()中的Func()不加override,则 运行顺序为: 进入Sub()类-运行Sub()构造函数-运行Base()构造函数-运行Base()构造函数中Func()函数-输出Base.Func- 继续运行Sub()构造函数中的Fun()-输出Sub.Func-运行obj.Func()-进入Base()-运行Func()-输出Base.Func() 若Sub()中保持override,但是实例化如下,则: Base obj = new Base(); 运行顺序为: 进入Sub()类-运行Sub()构造函数-运行Base()构造函数-运行Func()-输出Base.Func-运行obj.Func()- 进入Base()类-运行Base.Func()-输出Base.Func 若实例化方式为: Sub obj = new Sub(); 则: 进入Sub()类-运行Sub()构造函数-运行Base()构造函数-运行Sub()中override 重写Func()函数-输出Sub.Func-继续运行Sub()构造函数- 运行Sub()构造函数中的Func()函数-输出Sub()-运行obj.Func()-进入Sub()-运行Func()-输出Sub.Func()
class Base
{
public Base()
{
Func();
System.Console.WriteLine("Base()");
}
public virtual void Func()
{
System.Console.WriteLine("Base.func()");
}
}
class Sub : Base
{
public Sub()
{
Func();
System.Console.WriteLine("Sub()");
}
public override void Func()
{
Console.WriteLine("Sub.Func");
}
}
class Inherit1
{
public static void Run()
{
Base sub = new Sub();
sub.Func();
// 输出结果
// Sub.Func => Sub重载了Func,调用Sub.Func
// Base() => 先调用Base无参构造函数 => https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/using-constructors
// Sub.Func
// Sub() => 再调用Sub无参构造函数
// Sub.Func => 调用Sub.Func
}
} 