考慮下面的代碼片段:繼承例如
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
誰能請解釋我這背後的原因。另外,如果我們要在派生類中創建一個同名的方法,是否需要重寫基類的虛方法?
你的輸出是錯誤的。這應該說'你好從基類'和'你好從基類'。 – Khan