我一直在阅读Headfirst c#,我看到一部分代码让我对隐藏方法感到有些困惑,据我所知,隐藏方法会隐藏基类中具有相同名称的方法,但为什么在这段代码中,IDE仍然从基类调用方法?谢谢你,这里是代码:
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("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);
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 new void ReturnContents(Jewels safeContents, Owner owner)
{//this is the place that hiding the method ReturnContents from Locksmith
stolenJewels = safeContents;
Console.WriteLine("I'm stealing the contents! " + stolenJewels.Sparkle());
}
}
输出:
感谢您归还我的珠宝!闪闪发光,闪闪发光!