【发布时间】:2012-10-11 08:52:33
【问题描述】:
如何通过 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# 中通过参数获取属性的对象实例呢?
【问题讨论】:
-
我很确定您必须将对象和属性传递给
performOperation。 -
那么我无法从属性本身获取属性的对象实例吗?
-
我不这么认为,至少不是您在示例中访问该属性的方式。
-
我明白了。是的,我在示例中访问该属性的方式仅仅是我的意图的一个说明,因为我不确定我应该如何去做。我对 C# 的语法也有些陌生。谢谢。 :)
-
如果您获得该属性的
PropertyInfo。然后您可以使用DeclaringTypeproperty 获取声明成员的class,但看起来您无法获取实例。
标签: c# reflection instance-variables