在我的一生中,尽管有很多文档,但我从未理解过“方法隐藏”。
覆盖意味着使用派生类中的实现。我认为隐藏(通过使用“new”关键字)将意味着使用基类定义是否正确?在这种情况下,为什么要在继承类中编写方法?
实际上我的 2 个问题是:
- 隐藏是覆盖的对立面吗?
- new 关键字(用于隐藏)的作用是什么?何时/何地使用它?基础类?继承类?
- 有任何有用的真实示例吗?
最佳答案
你的理解有点偏差。
首先,覆盖一个方法意味着即使实例被转换为其基类型,新的实现也会被使用,因为在虚方法表中有一个合适的条目。
隐藏方法时,当实例被转换为其基类型时,将使用基实现,因为虚方法表中没有条目。
给定以下类定义:
public class Base
{
public virtual void Say()
{
Console.WriteLine("Hello World!");
}
}
public class A : Base
{
public new void Say()
{
Console.WriteLine("42");
}
}
public class B : Base
{
public override void Say()
{
Console.WriteLine("Goodbye, Cruel World!");
}
}
下面的代码会产生:
var a = new A();
var b = new B();
var aAsBase = a as Base;
var bAsBase = b as Base;
a.Say(); // 42
aAsBase.Say(); // Hello World!
b.Say(); // Goodbye, Cruel World!
bAsBase.Say(); // Goodbye, CruelWorld!
关于c# - 方法隐藏和 "new"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13185801/