例如,我有此类:
public class Car{
public string color;
public double price;
}
public class YellowCar{...}
public class RedCar{...}
并且在Car类中,我想编写一个方法,该方法将显示有关其派生类中“继承的”字段的信息,因此如下所示:
public class Car{
public string color;
public double price;
public void DisplayMethod(){
//display field **color** and field **price** from the instance of the YellowCar class
//...then display the same fields from the instance of the RedCar class
}
}
我不想使用将派生类实例作为参数并显示其字段的方法,因此我需要为每个实例多次调用此方法。程序架构中是否可以选择编写类似于我之前提到的方法的内容?如果它是什么,它是如何工作的?
嗯,这正是一种情况,继承可以帮助您。 (尽管如果差异保持在此“有限”范围内,则为此创建单独的类可能是过大的选择)
在您的第一堂课“汽车”中,您可以像这样简单地打印变量:
public class Car{
public string color;
public double price;
public void DisplayMethod(){
Console.WriteLine($"Color: {color}, price: {price.ToString("C")}");
}
}
然后,继承类将负责设置这些值。例如:
public class YellowCar : Car
{
public void YellowCar(double _price){
color = "yellow";
price = _price;
}
}
继承类(YellowCar
和RedCar
)可以访问他们继承的类(Car
)的字段,因此可以简单地对其进行设置。因此,如果编写类似DisplayMethod()
的打印方法,则可以打印这些值。
然后用法可能是这样:
public static void main(string[] args)
{
YellowCar expensiveYellowCar = new YellowCar(100000);
expensiveYellowCar.DisplayMethod();
YellowCar cheapYellowCar = new YellowCar(100);
cheapYellowCar .DisplayMethod();
Console.ReadLine();
}
应该提供输出:
“”颜色:黄色,价格:100'000,00€“
“”颜色:黄色,价格:100,00€“
((由于[C0]方法使用本地格式的货币格式,所以价格输出取决于您特定的Windows本地化。