书中所说new 有隐藏的作用,
如:class Vehicle
{
public int wheels;
protected float weight;
public Vehicle() { }
public Vehicle(int w, float g)
{
wheels = w;
weight = g;
}
public void Speak()
{
Console.WriteLine("the w vehicle is speaking!");
}
};
class Car : Vehicle
{
int passengers;
public Car(int w, float g, int p)
{
wheels = w;
weight = g;
passengers = p;
}
new public void Speak()
{
Console.WriteLine("car class");
}
static void Main()
{
Car obj = new Car(1, 2.2f, 3);
obj.Speak();
}
}现在这样在子类里有一个跟父类一样的方法,用了new public void Speak()
但在打印的时候为什么依然是打印子类的这个Speak()方法呢?
如:class Vehicle
{
public int wheels;
protected float weight;
public Vehicle() { }
public Vehicle(int w, float g)
{
wheels = w;
weight = g;
}
public void Speak()
{
Console.WriteLine("the w vehicle is speaking!");
}
};
class Car : Vehicle
{
int passengers;
public Car(int w, float g, int p)
{
wheels = w;
weight = g;
passengers = p;
}
new public void Speak()
{
Console.WriteLine("car class");
}
static void Main()
{
Car obj = new Car(1, 2.2f, 3);
obj.Speak();
}
}现在这样在子类里有一个跟父类一样的方法,用了new public void Speak()
但在打印的时候为什么依然是打印子类的这个Speak()方法呢?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货