在看C#高级编程第二版,有个例子看不懂,请教一下
using System;
namespace MortimerPhone5Funny
{
public class Customer
{
public string GetFunnyString()
{
return "Plain ordinary customer.Kaark! ";
}
}
public class Nevermore60Customer:Customer
{
public new string GetFunnyString()
{
return "Nervermore60.Nevermore! ";
}
}
public class MainEntryPoint
{
public static int Main(string[] args)
{
Customer Cust1;
Nevermore60Customer Cust2;
Cust1 = new Customer();
Console.WriteLine( "Customer referencing Customer: "+Cust1.GetFunnyString());
Cust1 = new Nevermore60Customer();
Console.WriteLine( "Customer referencing Nevermor60Customer: "+Cust1.GetFunnyString());
Cust2 = new Nevermore60Customer();
Console.WriteLine( "Nevermore60Customer referencing: "+Cust2.GetFunnyString());
return 0;
}
}
}
***************************************************************************
Cust1 = new Customer();
Console.WriteLine( "Customer referencing Customer: "+Cust1.GetFunnyString());
Cust1 = new Nevermore60Customer();
Console.WriteLine( "Customer referencing Nevermor60Customer: "+Cust1.GetFunnyString());
这一段,Cust1先是声明为Customer的一个实例,然后声明为Nevermore60Customer的实例,在Nervermore60Customer中新的GetFunnyString()方法不是已经把基类中的方法隐藏了么,为什么还是输出基类方法的结果?
------解决方案--------------------Customer Cust1;
Nevermore60Customer Cust2;
Cust1 = new Customer();
声明的时候,应该是声明了一个基类的对象
如果这样----
Nevermore60Customer Cust2 = new Nevermore60Customer();
(Customer )Cust2
然后再显示转换一下,你说他是调用哪个方法呢?
我只是说一下我的理解,请楼下继续