2011-04-13 135 views
3

我有以下情形:使用反射來獲得一個嵌套的屬性值

class A 
{ 
    string Foo; 
} 

Class B 
{ 
    A PropertyA; 
} 

Class C 
{ 
    B PropertyB; 
} 

使用.NET反射,如果我開始與對象C來到達A.Foo的價值是否有可能?我遇到的問題是這樣的: 我通過PropertyInfo對象到達A.但是,他們沒有存儲實例信息。因此,我不能做GetProperty(「Foo」)。GetValue(....),因爲我只有C類對象被傳入。

回答

4

您必須獲取每個屬性返回的對象,然後使用同樣的反射程序,以獲得下一個「層次」。

例如:

C instance = GetMyCInstance(); 

B propertyB = instance.GetType().GetProperty("PropertyB").GetValue(instance) as B; 
A propertyA = propertyB.GetType().GetProperty("PropertyA").GetValue(propertyB) as A; 
string Foo = propertyA.GetType().GetProperty("Foo").GetValue(propertyA) as string; 
+0

'乙propertyB = instance.GetType()的getProperty( 「PropertyB」)的GetValue(例如,NULL)爲B;'爲我工作,謝謝。 – travis 2012-11-20 00:16:00