using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LearnOverride
{
class Program
{
static void Main(string[] args)
{
Owner owner = new Owner();
Safe safe = new Safe();
Console.WriteLine("When \tLocksmith locksmith = new Locksmith();\n");
Locksmith locksmith = new Locksmith();
locksmith.OpenSafe(safe, owner);
Console.WriteLine("when ReturnContents() called from main,");
Jewels openedLocksmith = safe.Open("12345");
locksmith.ReturnContents(openedLocksmith, owner);
Console.WriteLine();
Console.WriteLine("\n\nWhen \tJewelThief jewelThief = new JewelThief();\n");
JewelThief jewelThief = new JewelThief();
jewelThief.OpenSafe(safe, owner);
Console.WriteLine("when ReturnContents() called from main,");
Jewels opened = safe.Open("12345");
jewelThief.ReturnContents(opened, owner);
Console.WriteLine();
Console.WriteLine("\n\nWhen \tLocksmith jewelThiefAsLocksmith = new JewelThief();\n");
Locksmith jewelThiefAsLocksmith = new JewelThief();
jewelThiefAsLocksmith.OpenSafe(safe, owner);
Console.WriteLine("when ReturnContents() called from main,");
Jewels j = safe.Open("12345");
jewelThiefAsLocksmith.ReturnContents(j, owner);
///JewelThief jewelThief = new Locksmith(); is error
Console.ReadKey();
}
}
class Jewels
{
public string Sparkle()
{
return "Sparkle, sparkle!";
}
}
class Safe
{
private Jewels contents = new Jewels();
private string safeCombination = "12345";
public Jewels Open(string combination)
{
if (combination == safeCombination)
return contents;
else
return null;
}
public void PickLock(Locksmith lockpicker)
{
lockpicker.WriteDownCombination(safeCombination);
}
}
class Owner
{
private Jewels returnedContents;
public void ReceiveContents(Jewels safeContents)
{
returnedContents = safeContents;
Console.WriteLine("Owner:Thank you for returning my jewels! " + safeContents.Sparkle());
}
}
class Locksmith
{
public void OpenSafe(Safe safe, Owner owner)
{
safe.PickLock(this);
Jewels safeContents = safe.Open(writtenDownCombination);
this.ReturnContents(safeContents, owner);
}
private string writtenDownCombination = null;
public void WriteDownCombination(string combination)
{
writtenDownCombination = combination;
}
public void ReturnContents(Jewels safeContents, Owner owner)
{
owner.ReceiveContents(safeContents);
}
}
class JewelThief : Locksmith
{
private Jewels stolenJewels = null;
public void ReturnContents(Jewels safeContents, Owner owner)
{
stolenJewels = safeContents;
Console.WriteLine("JewelThief:I'm stealing the contents! " + stolenJewels.Sparkle());
}
}
}
上面的代码没有覆盖方法 ReturnContents()。它在隐藏。所以我期待着声明
this.ReturnContents(safeContents, owner);
存在于 Locksmith 类中(在 OpenSafe() 方法内),如果从对象“JewelThief”引用,将调用 ReturnContents() 方法存在 Jewelthief 对象。
但每次它调用基类方法,ReturnContents。如何解释这种行为?