gpt4 book ai didi

c# - 新关键词混淆

转载 作者:行者123 更新时间:2023-11-30 20:05:06 25 4
gpt4 key购买 nike

全部 -

阅读了有关新关键字及其使用时间的各种文章:

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");
}
}

我的任何输出如下:

enter image description here

让我感到困惑的是,通过在派生类中使用 new 关键字实际上显示了基类的输出。是不是错了 - 新关键字不应该隐藏基类成员资格,因此不应打印 Animal is Talking 和 Animal is Dancing 的结果。

谢谢

最佳答案

"new"意味着该方法是"new"而不是“覆盖”。因此,如果您从基类中调用该名称的方法,它不会被覆盖,因此不会调用派生类。

关于c# - 新关键词混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11904601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com