【问题标题】:Can't print contents of list, it prints Namesspace and Classname instead无法打印列表的内容,而是打印命名空间和类名
【发布时间】:2019-10-27 23:08:15
【问题描述】:

我通过用户输入将汽车或卡车添加到列表中。后来我想将这些打印到 RichTextBox 中,问题是它打印的是 Namespace 和类名,而不是实际的内容。我的代码如下:

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();
    }
}

这可能看起来像重复,但所有其他问题及其 各自的答案似乎没有帮助。

【问题讨论】:

  • 你在一个对象实例上调用 ToString。尝试改用 Vehichles 属性。喜欢 v.Name
  • 实际内容是什么?您需要在类中覆盖 ToString() 方法以返回您想要的任何内容。默认的 ToString() 方法只返回命名空间和类名
  • 既然你在做v.ToString(),它会打印命名空间和类名,试试v.VehicleType.ToString()
  • 谢谢大家,v.Name 和 v.VehicleType.ToString() 变体成功了,干杯。

标签: c# .net list foreach printing


【解决方案1】:

您必须覆盖您班级的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 类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多