【发布时间】:2019-06-04 15:31:56
【问题描述】:
这是我的代码(只是主程序类之外的类)。
它有 2 个类:仅具有一些属性的 Vehicle,以及继承 Vehicle 并具有更多功能的 Car,例如 Car“Car()”的构造函数、打印特定汽车“PrintCarInfo()”信息的方法和用于Car 类打印创建的 Car 实例的数量。
public class Vehicle
{
protected double speed;
protected int wheels = 4;
protected string color;
protected string manufacturer;
}
public class Car : Vehicle
{
static int carCounter = 0;
public Car(double speed, string color, string manufacturer)
{
this.speed = speed;
this.color = color;
this.manufacturer = manufacturer;
Interlocked.Increment(ref carCounter);
}
public void PrintCarInfo()
{
Console.WriteLine("Speed of car is {0}", speed);
Console.WriteLine("Car has {0} wheels", wheels);
Console.WriteLine("Car is {0}", color);
Console.WriteLine("Car was made by {0}", manufacturer);
Console.WriteLine();
}
public static void NumberOfCars()
{
Console.WriteLine("Number of cars created: {0}", carCounter);
Console.WriteLine();
}
在我创建了一个新的 Car 实例后:Car car1 = new Car(120, "Red", "Porsche");,我如何在 PrintCarInfo() 方法中打印该特定实例的名称?
目前 PrintCarInfo() - 方法打印汽车的速度、车轮、颜色和制造商,但我想在它们之前打印特定实例的名称。
类似:Console.WriteLine("Info about {0}", "Insert instance reference here")
我想避免将实例作为方法的参数,例如car1.PrintCarInfo(car1);
如何引用创建的实例? (本例中为 car1)
我尝试过使用object carObject;,但没有成功。
【问题讨论】:
-
我认为这不会像您希望的那样容易。有 nameof() 但您必须在调用 PrintCarInfo 时使用它,而不是在其中。另一个简单的解决方案是给汽车一个名字(就像它有速度一样)。
-
您可以这样做:Console.WriteLine("关于 {0} 的信息", nameof(car1))。这必须在汽车类之外,就在调用 PrintCarInfo 之前,我认为这不是你想要的。
-
好的,就像@Joelius 提到的那样,最简单的方法是在构造函数中为汽车命名。
-
我会把它变成一个答案,这样你就可以接受它并将问题标记为已解决。见my answer