如果我有以下代码并希望迭代车辆列表并显示价格,我该如何访问该属性?
public class Vehicle
{
public string Name { get; set; }
public string Price { get; set; }
}
public class ElectricalDriven : Vehicle
{
public string SuperChargerCord { get; set; }
}
public class GasolinDriven : Vehicle
{
public string GasolineTank { get; set; }
}
var myListOfVechicles = new List<Vehicle>();
myListOfVechicles.Add(new ElectricalDriven { Name = "Tesla", Price = "100 000", SuperChargerCord = "Yellow cord"});
myListOfVechicles.Add(new GasolinDriven { Name = "Ford", Price = "50 000", GasolineTank = "Large VZ Tank"});
foreach (var row in myListOfVechicles)
{
Console.WriteLine($"- {row.Name}");
}
答案 0 :(得分:1)
问题是Vehicle
Value
属性,因此您无法以类型安全的方式提出要求。
有些选择是:
ToString
,以便类确定显示内容:virtual
方法添加到VEhivel like
GetDescription that returns a string if you don't want that string to override
ToString` Price
移至Vehicle
或ElectricalDriven
和GasolinDriven
都继承自的子类型。答案 1 :(得分:0)
在foreach中,您可以使用'is'运算符检查当前'row'是ElectricalDriven还是GasolinDriven,然后将该行转换为匹配的具体实现。应该是这样的:
if (row is ElectricalDriven)
{
Console.WriteLine($"Price: {((ElectricalDriven)row).Price}");
}
else if (row is GasolinDriven)
{
Console.WriteLine($"Price: {((GasolinDriven)row).Price}");
}
然而,你可以看到越多不同的车辆,越多的ifs。您应该在基类或界面中移动price属性。
编辑:看到作者将price属性移动到Vehicle类,您现在可以像访问Name属性一样访问它。
答案 2 :(得分:0)
如果要为Electric和Gasoline车辆定义一个唯一属性,并且能够从通用车辆类中检索其值,您可以声明一个虚方法并在继承类中覆盖它:
public class Vehicle
{
public string Name { get; set; }
public virtual string GetCustomProperty() { return string.Empty; }
}
public class ElectricalDriven : Vehicle
{
public string ElectricalVehicleProperty { get; set; }
public override string GetCustomProperty() { return ElectricalVehicleProperty; }
}
public class GasolinDriven : Vehicle
{
public string GasolinVehicleProprety { get; set; }
public override string GetCustomProperty() { return GasolinVehicleProprety; }
}
class Program
{
static void Main(string[] args)
{
var myListOfVechicles = new List<Vehicle>();
myListOfVechicles.Add(new ElectricalDriven { Name = "Tesla", ElectricalVehicleProperty = "100 000" });
myListOfVechicles.Add(new GasolinDriven { Name = "Ford", GasolinVehicleProprety = "50 000" });
foreach (var row in myListOfVechicles)
{
Console.WriteLine("Price: " + row.GetCustomProperty()); //will output 100,000 and 50,000
}
Console.Read();
}
}
答案 3 :(得分:0)
通过这样做:
var myListOfVechicles = new List<Vehicle>();
myListOfVechicles.Add(new ElectricalDriven { Name = "Tesla", Price = "100 000" });
myListOfVechicles.Add(new GasolinDriven { Name = "Ford", Price = "50 000" });
编译器会在 隐式转换为基类类型后,将子类的对象(如ElectricalDriven)分配给基类(Vehicle) 。 / p>
由于此转换,当您尝试访问该对象时,您正在访问仅具有 为了能够访问Name
基类成员的对象。Price
,您需要显式在访问其成员之前将对象强制转换为子类类型。最简单的例子你可以试试这个: string name, price;
foreach (var item in myListOfVechicles)
{
name = item is ElectricalDriven ?
(item as ElectricalDriven).Name :
(item as GasolinDriven).Name;
price = item is ElectricalDriven ?
(item as ElectricalDriven).Price :
(item as GasolinDriven).Price;
Console.WriteLine($"Name: {name} - Price: {price}");
}