2

如何通过 C# 中的参数获取属性的对象实例?我不确定它是否称为变量实例,但这就是我的意思:

在通常情况下,当我们这样做时,我们会在 C# 中获取变量的值:

void performOperation(ref Object property) {
   //here, property is a reference of whatever was passed into the variable
}

Pet myPet = Pet();
myPet.name = "Kitty";
performOperation(myPet.name);   //Here, what performOperation() will get is a string

我希望实现的是从类的属性中获取对象,例如:

void performOperation(ref Object property) {
   //so, what I hope to achieve is something like this:

   //Ideally, I can get the Pet object instance from the property (myPet.name) that was passed in from the driver class
   (property.instance().GetType()) petObject = (property.instnace().GetType())property.instance();  

    //The usual case where property is whatever that was passed in. This case, since myPet.name is a string, this should be casted as a string
   (property.GetType()) petName = property;   
}

Pet myPet = Pet();
myPet.name = "Kitty";
performOperation(myPet.name);   //In this case, performOperation() should be able to know myPet from the property that was passed in

instance()只是一个演示我想要获取属性的实例对象的虚拟方法。我对 C# 很陌生。这在概念上是我希望实现的,但我不确定如何在 C# 中做到这一点。我查看了反射 API,但我仍然不太确定应该使用什么来执行此操作。

那么,如何通过 C# 中的参数获取属性的对象实例呢?

4

1 回答 1

1

当您将属性值传递给方法时,例如:

SomeMethod(obj.TheProperty);

然后实现为:

SomeType foo = obj.TheProperty;
SomeMethod(foo);

基本上,您无法从中获取父对象。您需要单独传递它,例如:

SomeMethod(obj, obj.TheProperty);

此外,请记住,一个值可以是任意数量的对象的一部分。字符串实例可以用在零个、一个或“许多”对象中。你问的基本上是不可能的。

于 2012-10-21T09:01:57.960 回答