2014-07-02 127 views
0

因此,讓我們從代碼開始,這樣我可以更好地解釋我自己。我有MyClass類,其中包含一個int字段,還有Foo類包含MyClass作爲字段。我想使用反射從MyClass中獲取int字段的值。獲得另外一個領域的領域中的領域的價值

public class Foo 
{ 
public MyClass myClass; 
} 

public class MyClass 
{ 
public int Integer = 1; 
} 

當我使用

Foo f = new Foo(); 
foreach(FieldInfo fi in f.GetType().GetFields()) 
{ 
//lets say now it enumerating myClass field 
foreach(FieldInfo fi2 in fi.FieldType.GetFields()) 
{ 
    return fi2.GetValue(f); //Here I need to use f.myClass, but I can't 
    //because it's generic method and I don't know what type I'm currently 
    //enumerating, so just typing f.myClass won't make it 
} 
} 

的問題是如何獲取f.myClass.Integer的價值?
在此先感謝,
保羅

+0

在此處查看您的用例會很有趣。 –

+0

@ByteBlast我正在爲Unity3D引擎中的項目編寫自定義序列化解決方案。所以序列化類會看起來像這樣Serializer {void Serialize(string fileName,object serializedObject); T反序列化(string fileName,out object deserializedObject); } – superpawelTV

回答

-1

爲什麼你必須在這種情況下使用反射的任何特定原因?如果您只是試圖瞭解該實例方法的值,則可以執行以下操作:

Foo f = new Foo(); 
var myInt = f.myClass.Integer; 
+0

哦,我正在爲Unity3D引擎中的項目編寫自定義序列化解決方案。所以序列化類將看起來像這樣 class Serializer void Serialize(string fileName,object serializedObject); T反序列化(string fileName,out object deserializedObject); } (奇怪的人低估了這個答案) – superpawelTV