如果我有这样的课程
public class Car
{
private string number;
private string brand;
private string model;
private double kilometers;
public Car(string n,string b,string m,double km)
{
number = n;
brand = b;
model = m;
kilometers = km;
}
}
像这样的数组
Car[] car;
car = new Car[5];
car[0] = new Car("01", "Audi", "R8", 2593);
car[1] = new Car("02", "Jaguar", "F-Type", 12432);
car[2] = new Car("03", "Porsche", "Cayman", 87643);
car[3] = new Car("04", "Mclaren", "675 LT", 34265);
car[4] = new Car("05", "Ferrari", "458 Italia", 2145);
假设i
是数组的位置。
如何在一行中显示car[i]
中的所有内容。
答案 0 :(得分:10)
您可以覆盖ToString
类
Car
public class Car
{
.....
public override string ToString()
{
return string.Format("{{ Number = \"{0}\", Brand= \"{1}\", Model = \"{2}\", Kilometers = \"{3}\" }}",
this.number, this.brand, this.model, this.kilometers);
// if using C# 6.0 you can use string interpolation instead.
// return $"{{ Number = \"{this.number}\", Brand= \"{this.brand}\", Model = \"{this.model}\", Kilometers = \"{this.kilometers}\" }}";
}
}
然后只需将它们全部打印在Console
foreach (var c in car)
{
Console.WriteLine(c);
// Console.WriteLine(Object) will call the ToString method of input Object to produce its string representation, and the resulting string is written to the standard output stream.
}
或者只打印其中一个,例如Console.WriteLine(car[i]);