新的关键字混乱

Pat*_*ick 2 .net c#

全部 -

已阅读有关新关键字的各种文章以及何时应该使用它:

MSDN - http://msdn.microsoft.com/en-us/library/6fawty39(v=vs.80).aspx

StackOverflow - 在与基类成员具有相同名称的派生类成员中使用new关键字的好处

这是我为实践这个概念而编写的示例代码

    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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我的任何输出如下:

在此输入图像描述

令我困惑的是,通过在derieved类中使用new关键字实际上显示了基类的输出.不是错误 - 不是新的关键字应该隐藏基类成员,所以动物是说话和动物跳舞的结果不应该打印.

谢谢

Pet*_*hie 7

"new"表示方法是"new"而不是"override".因此,如果从基数调用该名称的方法,则它尚未被覆盖,因此不会调用派生.