我如何在 class 的方法中引用创建的 class 实例?

How do i reference created instance of a class inside class's method?

这是我的代码(只是主程序 class 之外的 classes)。

它有 2 个 classes:仅具有一些属性的 Vehicle,以及继承 Vehicle 并具有更多功能的 Car,例如 Car 的构造函数 "Car()",打印特定汽车信息的方法 "PrintCarInfo()" 和 Car 的静态方法 class 打印 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; 但没有成功。

使用虚拟 property/method 到 return 所需的标签。在基 class 的输出部分引用虚拟 property/method。然后它会选择正确实例的标签。 示例:

class Program
{
    static void Main(string[] args)
    {
        Vehicle v = new Vehicle();
        Car c = new Car();

        Console.WriteLine("Testing Vehicle base output");
        v.PrintInfo();
        Console.WriteLine("Testing Car inherited output");
        c.PrintInfo();

        return;
    }
}

class Vehicle
{
    public virtual string MyTypeName() { return "Vehicle"; }

    public void PrintInfo()
    {
        Console.WriteLine(string.Format("Type: {0}", this.MyTypeName()));
    }
}

class Car : Vehicle
{
    public override string MyTypeName() { return "Car"; }
}

这导致以下输出

Testing Vehicle base output
Type: Vehicle
Testing Car inherited output
Type: Car

正如我在评论中所写:

I don't think that'll work as easily as you might hope for. There is nameof() but you'd have to use this at the call to PrintCarInfo, not inside it. The other simple solution is to give the car a name (just like it has a speed).

据我所知,无法在被调用函数中使用 nameof。我知道 .net 有一些疯狂的属性,但我从未听说过这样的东西。

Op 说他们给每辆车取了一个名字,如果不是解决这个问题的最佳方法,那也是一个很好的名字。