获取对象的实例名称中没有对象类型名称C#4.0对象、名称、实例、类型

2023-09-03 03:41:55 作者:奈何桥上唱征服

假设这种类型的:

public class Car { } 

和我创建了一个实例:

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
   }

}

正如我发现在$ C C的的GetName 方法必须使用对象类型$(型号)并返回实例是myCar在本实施例中的名字?你有什么建议,有什么办法做到这一点?

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? what is your suggestion is there any way to do this?

更新 这个怎么样:

public class Car {

  public string Title { get; set; }

}

和我传递给目标: target.Model = Car.Title

的GetName()方法返回标题

推荐答案

没有,这是不可能的。为什么?因为 myCar 仅仅是一个的名称的为你的实例的在你设置的变量范围。什么被保存到 target.Model 是引用的到实例。所以,在你的样品code,这两种 myCar target.Model 引用车,只是名称不同。它们的名称是相当不重要的程序的执行,它只是我们用来进行谈论情况下更容易把戏。

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. What gets saved to target.Model is a reference to the Car instance. So, after your sample code, both myCar and target.Model reference the same instance of Car, just with different names. 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.