c# - 方法擦除:为什么说派生类的方法隐藏了基类,反之呢?
问题描述
class Animal
{
public void Foo() { Console.WriteLine("Animal::Foo()"); }
}
class Cat : Animal
{
public void Foo() { Console.WriteLine("Cat::Foo()"); }
}
class Test
{
static void Main(string[] args)
{
Animal a;
a = new Cat();
a.Foo(); // output --> "Animal::Foo()"
}
}
编译器警告说:
Cat.Foo 隐藏了继承的成员
然而,输出实际上来自基类。所以对我来说,似乎反过来,我调用的那个被基类中的那个隐藏了。
解决方案
你的程序的输出是Animal
类的实现,Foo
因为引用的类型是Animal
和非Cat
。
如果引用的类型为Cat
,则输出为"Cat::Foo()"
.
类的Foo
方法Cat
隐藏了类的Foo
方法,Animal
因为基类不能也不应该知道它们的派生类,而派生类是并且必须知道它们的基类。
要故意隐藏基类的成员,请使用new
修饰符。这将告诉编译器隐藏是故意的,并将抑制警告。
推荐阅读
- ruby-on-rails - Rails 嵌套模型验证仅在填充某些内容时运行
- webforms - 如果页面有两个用户控件引用,则隐藏 Web 表单应用程序中的按钮
- c++ - 使用 #pragma 注释时出现 LNK2019 错误,被 /VERBOSE 输出混淆
- python - 访问和检查对象实例的属性,例如登录页面的“用户”对象中的“用户名”属性
- ios - 构建正在从 iTunes 连接中消失
- javascript - 快递返回帖子信息由另一个函数处理
- c# - C# 读取文件并搜索更改
- python - Python,Docker - “ascii”编解码器无法编码字符
- r - R根据辅助数据框更改数据框值
- javascript - ChartJS:在工具提示中显示混合图表的所有标签