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 的值?
在此先感谢,
保罗

4

1 回答 1

-1

在这种情况下必须使用反射的任何特殊原因?如果您只是想获取该实例方法的值,则可以执行以下操作:

Foo f = new Foo();
var myInt = f.myClass.Integer;
于 2014-07-02T20:13:16.840 回答