Get the instance name of the object no the object type name in C# 4.0

后端 未结 3 1741
自闭症患者
自闭症患者 2021-01-13 02:49

Assume this type:

public class Car { } 

And I create an instance of that:

Car myCar = new Car();

Target target = new Targe         


        
3条回答
  •  攒了一身酷
    2021-01-13 03:05

    Objects do not have a name, unless they explicitly have a way to store their name. myCar is a local variable - the object itself (the Car) does not know that you are referring to it by the name myCar. To illustrate:

    Car myCar = new Car();
    Car car2 = myCar;
    Car car3 = myCar;
    

    Now all three variables refer to the same Car.

    If you want cars to have names, you could do

    public class Car 
    {
        public string Name { get; set; }
    } 
    

    and then assign and read whatever name you want it to have.

提交回复
热议问题