【问题标题】:new Keyword confusion新的关键字混淆
【发布时间】:2016-05-01 22:40:39
【问题描述】:

全部 -

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

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

StackOverflow - benefit of using new keyword in derived class member having same name with base class member

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

    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 的结果。

谢谢

【问题讨论】:

标签: c# .net


【解决方案1】:

“新”表示该​​方法是“新的”而不是“覆盖”。因此,如果您从基类调用该名称的方法,它还没有被覆盖,因此不会调用派生类。

【讨论】:

    【解决方案2】:

    这也让我感到困惑,但简单地说:

    new 关键字对父级隐藏子级成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多