我真的不了解C#中的一种行为:
class Animal {
public string species = "animal";
public void Introduce() {
Console.WriteLine(species);
}
}
class Cat: Animal {
new public string species = "cat";
// public void Introduce() {Console.WriteLine(species);}
}
class Program
{
static void Main(string[] args)
{
var cat = new Cat();
cat.Introduce();
}
}
这段代码在执行时输出>>> animal
。
对我而言,由于Cat继承了Animal,因此调用cat.Introduce应该在“ cat实例的范围内”调用Animal.Introduce。即我不明白为什么程序选择species
动物领域而不是猫领域...
我知道我可以使用变通办法,但是我相信我缺少有关c#设计的一些知识,有人可以解释这种现象吗?
谢谢
我不明白为什么该程序选择动物的物种领域而不是猫的物种...
因为new
修饰符隐藏了继承的species
成员...,但仅在Cat
实例内部。您在基类上调用该方法,该基类仅知道其自己的species
成员。
如果给您的Cat
类一个IntroduceCat()
方法,然后在其中打印species
并调用它,则会看到“ cat”字符串正在打印。
如果要覆盖派生类中的成员,则必须将该成员标记为virtual
基类中的成员,并将override
其标记为派生类中的成员。但是您不能对字段执行此操作,因此必须将其设置为属性。
但是您可能只想分配一个不同的值,并且可以在构造函数中进行分配。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句