【发布时间】:2016-05-08 09:06:00
【问题描述】:
在基于类型引用对象的方法覆盖的情况下,将决定保留方法调用。 方法隐藏的情况下,将根据对象方法调用的类型来决定。
谁能解释一下覆盖+隐藏中的方法调用决策。
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public override void DoIt()
{
}
}
public class Derived1 : Derived
{
public new void DoIt()
{
}
}
class Program
{
static void Main(string[] args)
{
Base b = new Derived();
Derived d = new Derived();
#1 b.DoIt(); // Calls Derived.DoIt
#2 d.DoIt(); // Calls Derived.DoIt
b = new Derived1();
d = new Derived1();
#3 b.DoIt(); // Calls Derived.DoIt
#4 d.DoIt();
}
}
#1 和 #2 调用 Derived.DoIt 因为运行时多态性。
#4 称为 Derived.DoIt,因为 d 是 Derived 类型(方法隐藏)。
但是为什么 #3 调用 Derived.DoIt。
在c#中覆盖加隐藏时的调用顺序是什么。
提前致谢
【问题讨论】:
-
你可以这样想:
Derived1有两个DoIt方法——一个继承自Base类,另一个在Derived1本身中声明。当您在 Base 或 Derived 类型的实例上调用 DoIt 时 - 他们只知道一种 DoIt 方法而对另一种方法一无所知,因此会调用此方法。
标签: c# overriding method-hiding