我添加了几行代码来编译代码:
void Main()
{
var t = new Test();
t.Run();
}
class ParaA {}
class ParaB : ParaA {}
class ParaC : ParaB {}
class TheBaseClass
{
public void DoJob (ParaA a){Console.WriteLine ("DoJob in TheBaseClass is being invoked");}
}
class TheDerivedClass : TheBaseClass
{
public void DoJob (ParaB b){Console.WriteLine ("DoJob in TheDerivedClass is being invoked");}
}
public class Test
{
public void Run()
{
//Case 1: which version of DoJob() is being called?
TheDerivedClass aInstance= new TheDerivedClass ();
aInstance.DoJob(new ParaA ());
//Case 2: which version of DoJob() is being called?
TheBaseClass aInstance2= new TheDerivedClass ();
aInstance2.DoJob(new ParaA ());
//Case 3: which version of DoJob() is being called?
TheBaseClass aInstance3= new TheDerivedClass ();
aInstance3.DoJob(new ParaB ());
//Case 4: which version of DoJob() is being called?
TheBaseClass aInstance4= new TheDerivedClass ();
aInstance4.DoJob(new ParaC ());
}
}
产生输出:
DoJob in TheBaseClass is being invoked
DoJob in TheBaseClass is being invoked
DoJob in TheBaseClass is being invoked
DoJob in TheBaseClass is being invoked
即每次都调用基类方法。
在案例 1 中,它被调用是因为参数是 ParaA,而 ParaA 不是 ParaB。在其他情况下,调用它是因为对象实例的类型为“TheBaseClass”。
下面是修改后的相同代码以说明方法重载:
void Main()
{
var t = new Test();
t.Run();
}
class ParaA {}
class ParaB : ParaA {}
class ParaC : ParaB {}
class TheBaseClass
{
public virtual void DoJob (ParaA a){Console.WriteLine ("DoJob in TheBaseClass is being invoked");}
}
class TheDerivedClass : TheBaseClass
{
public override void DoJob (ParaA b){Console.WriteLine ("DoJob in TheDerivedClass is being invoked");}
}
public class Test
{
public void Run()
{
//Case 1: which version of DoJob() is being called?
TheDerivedClass aInstance= new TheDerivedClass ();
aInstance.DoJob(new ParaA ());
//Case 2: which version of DoJob() is being called?
TheBaseClass aInstance2= new TheDerivedClass ();
aInstance2.DoJob(new ParaA ());
//Case 3: which version of DoJob() is being called?
TheBaseClass aInstance3= new TheDerivedClass ();
aInstance3.DoJob(new ParaB ());
//Case 4: which version of DoJob() is being called?
TheBaseClass aInstance4= new TheDerivedClass ();
aInstance4.DoJob(new ParaC ());
}
}
现在的输出是:
DoJob in TheDerivedClass is being invoked
DoJob in TheDerivedClass is being invoked
DoJob in TheDerivedClass is being invoked
DoJob in TheDerivedClass is being invoked
每次都会调用 DerivedClass 方法,因为对象是“TheDerivedClass”类型。