简体   繁体   English

获取对象的实例名称,而不是C#4.0中的对象类型名称

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

Assume this type: 假设这种类型:

public class Car { } 

And I create an instance of that: 我创建了一个实例:

Car myCar = new Car();

Target target = new Target();
target.Model = myCar;

And this is another Type: 这是另一种类型:

public class Target {

   public object Model { get; set; }

   string GetName(){

     //Use Model and return myCar in this Example
   }

}

As I showed in code the GetName method must use an object type ( Model ) and returned the name of instance that is myCar in this example? 正如我在代码中所示, GetName方法必须使用对象类型( Model )并在此示例中返回myCar实例的名称? what is your suggestion is there any way to do this? 你有什么办法可以做到这一点?

Update How about this: 更新如何:

public class Car {

  public string Title { get; set; }

}

And I pass to target: target.Model = Car.Title 我传递给目标: target.Model = Car.Title

And GetName() method returned Title ? 并且GetName()方法返回Title

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 . myCar是一个局部变量 - 对象本身( Car不知道你是用名字myCar来引用它的。 To illustrate: 为了显示:

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

Now all three variables refer to the same Car . 现在所有三个变量都指向 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. 然后分配并读取您希望它拥有的任何名称。

No, this is not possible. 不,这是不可能的。 Why? 为什么? Because myCar is only a name for your Car instance inside the scope which you set up the variable for. 因为myCar只是您为其设置变量的范围Car实例的名称 What gets saved to target.Model is a reference to the Car instance. 保存到target.Model是对Car实例的引用 So, after your sample code, both myCar and target.Model reference the same instance of Car , just with different names. 因此,在您的示例代码之后, myCartarget.Model引用相同的Car实例,只是使用不同的名称。 The names themselves are rather unimportant to the execution of the program, it's just a trick we use to make talking about instances easier. 这些名称本身对于程序的执行并不重要,它只是我们用来简化实例讨论的技巧。

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 (ie relying on the variable name) is a bad practice. 此外,链接代码和数据(即依赖于变量名称)是一种不好的做法。

If you want Car to have some name, then name it explicitly : 如果您希望Car有一些名称,请明确命名:

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

Car myCar = new Car { Name = "myCar" };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM