Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在类的方法中引用已创建的类实例?_C#_Class_Methods_Instance - Fatal编程技术网

C# 如何在类的方法中引用已创建的类实例?

C# 如何在类的方法中引用已创建的类实例?,c#,class,methods,instance,C#,Class,Methods,Instance,这是我的代码,只是主程序类之外的类 它有两个类:Vehicle只有一些属性,Car继承Vehicle并具有更多功能,如Car-Car的构造函数、打印特定汽车信息的方法PrintCarInfo和打印汽车创建实例数的Car类静态方法 public class Vehicle { protected double speed; protected int wheels = 4; protected string color; protected string manufactu

这是我的代码,只是主程序类之外的类

它有两个类:Vehicle只有一些属性,Car继承Vehicle并具有更多功能,如Car-Car的构造函数、打印特定汽车信息的方法PrintCarInfo和打印汽车创建实例数的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 car1=新车120,红色,保时捷;,如何在PrintCarInfo-method中打印特定实例的名称

目前,PrintCarInfo方法打印汽车的速度、车轮、颜色和制造商,但我想在它们之前打印特定实例的名称

类似于:Console.WriteLineInfo关于{0},在此处插入实例引用

我希望避免将实例作为方法的参数,例如car1.PrintCarInfocar1

如何引用已创建的实例?在这种情况下是car1


我试着玩弄这个东西;但是没有成功。

使用虚拟属性/方法返回所需的标签。在基类的输出部分引用虚拟属性/方法。然后它将拾取正确实例的标签。 例如:

这将产生以下输出

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

如我在评论中所述:


我认为这不会像你希望的那样容易。有nameof,但您必须在调用PrintCarInfo时使用它,而不是在它内部。另一个简单的解决方案是给汽车起个名字,就像它有速度一样

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


Op说他们给每辆车起了一个名字,如果不是解决这个问题的最好办法,这是一个非常好的办法。

我认为这不会像你希望的那样容易。有nameof,但您必须在调用PrintCarInfo时使用它,而不是在它内部。另一个简单的解决方案是给汽车起一个名字,就像它有速度一样。你可以这样做:Console.WriteLineInfo about{0},nameofcar1。这必须在汽车类之外,就在调用PrintCarInfo之前,我认为这不是你想要的。好吧,就像@Joelius提到的,最简单的方法是在构造函数中为汽车命名。我将把它转换为一个答案,这样你就可以接受它,并将问题标记为已解决。看见
Testing Vehicle base output
Type: Vehicle
Testing Car inherited output
Type: Car