全部 -
已阅读有关新关键字以及何时使用的各种文章:
MSDN - http://msdn.microsoft.com/en-us/library/6fawty39(v=vs.80).aspx
StackOverflow -在与基类成员同名的派生类成员中使用新关键字的好处
这是我为实践这个概念而编写的示例代码
static void Main(string[] args)
{
Animal a2 = new Dog();
a2.Talk();
a2.Sing();
a2.Greet();
a2.Dance();
Console.ReadLine();
}
class Animal
{
public Animal()
{
Console.WriteLine("Animal constructor");
}
public void Talk()
{
Console.WriteLine("Animal is Talking");
}
public virtual void Sing()
{
Console.WriteLine("Animal is Singing");
}
public void Greet()
{
Console.WriteLine("Animal is Greeting");
}
public virtual void Dance()
{
Console.WriteLine("Animal is Dancing");
}
}
//Derived Class Dog from Animal
class Dog : Animal
{
public Dog()
{
Console.WriteLine("Dog Constructor");
}
public new void Talk()
{
Console.WriteLine("Dog is Talking");
}
public override void Sing()
{
//base.Sing();
Console.WriteLine("Dog is Singing");
}
public new void Dance()
{
Console.WriteLine("Dog is Dancing");
}
}
我的任何输出如下:
令我困惑的是,通过在派生类中使用 new 关键字实际上显示了基类的输出。这不是错误的吗? new 关键字不应该隐藏基类成员资格,因此不应该打印 Animal is Talking 和 Animal is Dancing 的结果。
谢谢