如何通过 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# 中的参数获取属性的对象实例呢?