2015-11-06 62 views
2

當前我試圖從嵌套類獲取屬性的值。不幸的是我得到一個參數爲object。我知道內部結構,但我無法解決,如何達到財產。通過雙重嵌套類的反射獲取值

爲了方便測試我編寫一些代碼行:

namespace ns{ 
    public class OuterClass{ 
     public InnerClass ic = new InnerClass(); 
    } 
    public class InnerClass { 
     private string test="hello"; 
     public string Test { get { return test; } } 
    } 
} 

直接調用這個很簡單:

var oc = new ns.OuterClass(); 
string test = oc.ic.Test; 

但是,當我試圖讓通過反射的價值,我碰上System.Reflection.TargetException

object o = new ns.OuterClass(); 
var ic_field=o.GetType().GetField("ic"); 
var test_prop = ic_field.FieldType.GetProperty("Test"); 
string test2 = test_prop.GetValue(???).ToString(); 

作爲中的對象,我必須使用什麼??

回答

3

你需要得到icFieldInfo值:

object ic = ic_field.GetValue(o); 

然後,你傳遞給test_prop.GetValue

string test2 = (string)test_prop.GetValue(ic, null); 
+1

是的,來闡述,當你使用'的getProperty( 「SomeName」 )''你只是獲得關於屬性結構的元數據('PropertyInfo'),而不是實際的屬性值本身以及它引用的對象。 PropertyInfo對類的實例一無所知,因此'GetValue'需要你給它一個實際的引用來指向你想要執行屬性訪問的對象。 – AaronLS

+0

謝謝!我只是自己找到了它。我把'ic_field.GetValue(o)'放在三個'???'的地方,它工作。很好的答案。 +1並接受它。 – Shnugo