考虑下面的代码片段:
class BaseClass
{
public void SayHi()
{
Console.WriteLine("Hi from base class");
}
public virtual void SayHello()
{
Console.WriteLine("Hello from base class");
}
}
class DerivedClass : BaseClass
{
public void SayHi()
{
Console.WriteLine("Hi from derived class");
}
public new void SayHello()
{
Console.WriteLine("Hello from derived class");
}
}
class Program
{
static void Main(string[] args)
{
BaseClass _object = new DerivedClass();
_object.SayHi();
_object.SayHello();
Console.ReadKey();
}
}
上面的输出显示:
Hi from base class
Hi from derived class
谁能解释一下这背后的原因。另外,如果我们在派生类中创建同名方法,是否不需要重写基类的虚方法?