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

时间:2012-10-21 08:47:28

标签: c# reflection instance-variables

如何通过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#中这样做。我查看了Reflection API,但我仍然不确定应该使用什么来做这件事。

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

1 个答案:

答案 0 :(得分:1)

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

SomeMethod(obj.TheProperty);

然后它被实现为:

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

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

SomeMethod(obj, obj.TheProperty);

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