c# - 继承层次结构中的虚拟键、覆盖键和新键
问题描述
我有以下代码:
class Animal
{
public virtual void Invoke()
{
Console.WriteLine("Animal");
}
}
class Dog : Animal
{
public override void Invoke()
{
Console.WriteLine("Dog");
}
}
class Dobberman : Dog
{
public new void Invoke()
{
Console.WriteLine("Dobberman");
}
}
class Program
{
static void Main(string[] args)
{
Animal dog = new Dobberman();
dog.Invoke();
Dobberman dog2 = new Dobberman();
dog2.Invoke();
}
}
为什么它会在第一个输出中打印“Dog”?为什么第二个是“杜伯曼”?引擎盖下发生了什么?
解决方案
Invoke
是虚拟的Animal
,被 覆盖Dog
,并被(SIC)隐藏Dobberman
请记住,方法在编译时绑定,然后在运行时查找虚拟方法的覆盖。
所以绑定如下:
Animal dog = new Dobberman();
// binds to Dog.Invoke since the variable type is Animal,
// the runtime type is Dog
// and Dog overrides Animal.Invoke
dog.Invoke();
Dobberman dog2 = new Dobberman();
// binds to Dobberman.Invoke since the variable type is Dobberman
dog2.Invoke();
推荐阅读
- android - 使用 React Native FS 将文件写入 Android 外部存储
- javascript - 从字符串中获取数字并插入css
- c# - 我们可以忽略类属性中的 ac# 列表吗?
- c# - 无法使用正则表达式否定单词组合
- linux - 用出现的字符串替换文本文件中的字符串
- sql - 关于简单 SQL 选择的建议
- javascript - 从 django 网站中的 javascript 发送到 views.py 的数据不正确
- python - 如何成功终止通过子进程运行创建的子进程
- java - 我无法从模块化 Maven 项目(在 IntelliJ 中)的测试目录中运行我的应用程序
- react-native - 使用 react-native-scrollable-tabview 获取数据