通过用户输入将汽车或卡车添加到列表中。后来我想将它们打印到RichTextBox,问题是它打印Namespance和类名而不是实际内容。我的代码如下:
Vehicle v0 = new Car(vehicleTypeString, textBoxPlate.Text,
textBoxMake.Text, textBoxColour.Text, DateTime.Now,
Car.parkingSpotInput); // These are just user input
vehicles.Add(v0);
foreach (Vehicle v in vehicles)
{
if (v is Car)
{
richTextBoxCar.Text = v.ToString();
}
else
{
richTextBoxTruck.Text = v.ToString();
}
}
这可能看起来像重复的,但其他所有问题及其 各自的答案似乎没有帮助。
答案 0 :(得分:0)
您必须重写类的ToString()
方法。像这样:
public class Car
{
private string VehicleType;
private string BoxPlate;
private string BoxColour;
private string BoxMake;
private DateTime CreationTime;
private string ParkingSpotInput;
public Car(string vehicleType, string boxPlate, string boxMake, string boxColour, DateTime creationTime, string parkingSpot)
{
this.VehicleType = vehicleType;
this.BoxPlate = boxPlate;
this.BoxColour = boxColour;
this.CreationTime = creationTime;
this.ParkingSpotInput = parkingSpot;
}
public override string ToString()
{
return $"VehicleType: {this.VehicleType}, BoxPlate: {this.BoxPlate}, BoxColour: {this.BoxColour}");
}
}
当然,您可以自行决定要使用ToString
方法输出什么。
以及您的ToString
类的类似Truck
实现。