在“抽象与虚函数的区别”中了解抽象与虚方法之间的区别。
我有一个与virtual
和有关的疑问new
让我们考虑如下示例代码
class MainClass
{
public static void Main()
{
DerivedClass _derived = new DerivedClass();
_derived.SayHello();
_derived.SayGoodbye();
Console.ReadLine();
}
}
public abstract class AbstractClass
{
public void SayHello()
{
Console.WriteLine("Hello - abstract member\n");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye- abstract member \n");
}
//public abstract void SayGoodbye();
}
public class DerivedClass : AbstractClass
{
public new void SayHello()
{
Console.WriteLine("Hi There - Hiding base class member");
}
//public override void SayGoodbye()
//{
// Console.WriteLine("See you later - In derived class OVERRIDE function");
//}
public new void SayGoodbye()
{
Console.WriteLine("See you later - In derived class I'm in NEW member");
}
}
我的问题:
在派生类中,如果我调用函数,如何override
执行new
相同的SayGoodbye
功能?我什么时候需要去选择/喜欢它们?在哪些实时场景中我需要更喜欢?