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

后端 未结 3 1739
自闭症患者
自闭症患者 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:01

    There is no such thing as "name of the instance". What you're saying about is the name of the specific reference to the object; there could be many references to the same object, all with different names. Also, linking code and data (i.e. relying on the variable name) is a bad practice.

    If you want Car to have some name, then name it explicitly:

    public class Car {
        public string Name { get; set; }
    } 
    
    Car myCar = new Car { Name = "myCar" };
    

提交回复
热议问题