2012-10-21 26 views
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#中的參數獲取屬性的對象實例?

+0

我敢肯定,你將不得不將對象以及屬性傳遞給'performOperation'。 – ChrisF

+0

因此,我不能從屬性本身獲取屬性的對象實例嗎? – Carven

+0

我不這麼認爲,至少不是您在示例中訪問過該屬性的方式。 – ChrisF

回答

1

當你的屬性值傳遞給方法,例如:

SomeMethod(obj.TheProperty); 

然後,它是這樣實現的:

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

無法得到父對象,基本上。你需要的是單獨通過,例如:

SomeMethod(obj, obj.TheProperty); 

另外,請記住,一個值可以是對象的任何數量的部分。字符串實例可以用於零個,一個或「多個」對象。你問的是根本不可能的。

相關問題