2
如何通過C#中的參數獲取屬性的對象實例?我不知道這是否就是所謂的變量實例,但這裏是我的意思是:如何通過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#中的參數獲取屬性的對象實例?
我敢肯定,你將不得不將對象以及屬性傳遞給'performOperation'。 – ChrisF
因此,我不能從屬性本身獲取屬性的對象實例嗎? – Carven
我不這麼認爲,至少不是您在示例中訪問過該屬性的方式。 – ChrisF