2014-07-02 130 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