我怎样才能反思并从这个内部阶级中获取价值?

时间:2017-03-27 22:25:01

标签: c# reflection

用户正在向我传递一个带有类名的字符串和另一个带有该类字段的字符串,我应该用它来提取一些信息。这里有几个示例类;它们都继承自相同的基类:

public class PersonRow : Row
{
   public static readonly RowFields Fields = new RowFields.Init();

   public class RowFields : RowFieldBase
   {
      public Int32Field Id;
      public StringField FirstName;
      public StringField LastName;
   }

}


public class AutomobileRow : Row
{
  public static readonly RowFields Fields = new RowFields.Init();

  public class RowFields : RowFieldBase
  {
     public Int32Field Id;
     public StringField PaintColor;
     public StringField EngineSize;
  }
}

用户会给我一些类似'PersonRow'和'FirstName'的内容,我需要从中潜入FirstName字段并提取其中名为Expression的成员的值。

我将在内部详细说明Int32FieldStringField正在做什么,但只要说这两种类型都有Expression成员,这是我需要使用的字符串

我正在尝试使用反射来做到这一点,并且已经做到了这一点:

var myClassType = Type.GetType("PersonRow");
var myFields = myClassType.GetField("Fields", BindingFlags.Public | BindingFlags.Static);
var fieldListing = myFields.GetValue(null);

...此时fieldListing是一个对象,它位于引擎盖下,属于PersonRow.RowFields类型。但是我有点困惑,因为我不确定如何枚举该数组并从我感兴趣的字段中提取Expression值?

1 个答案:

答案 0 :(得分:1)

我稍微修改了一下并找出了你的模特,最后得到了这个:

public class PersonRow
{
    public static readonly RowFields Fields = new RowFields();

    public class RowFields
    {
        public StringField FirstName = new StringField();
        public StringField LastName = new StringField();
    }
}

public class StringField
{
    public StringField()
    {
        expr = Expression.Constant("It worked!");
    }
    public Expression expr { get; set; }
    public string str { get; set; }
}

现在,基本上我们正在寻找PersonRow.Fields.FirstName.expr的值,可以使用以下代码完成:

var personRowType = typeof(PersonRow);

var fieldsField = personRowType.GetField("Fields", BindingFlags.Public | BindingFlags.Static);
var fieldsObj = fieldsField.GetValue(null);

var firstNameField = fieldsField.FieldType.GetField("FirstName");
var firstNameObj = firstNameField.GetValue(fieldsObj);

var exprProp = firstNameField.FieldType.GetProperty("expr");
var exprObj = (ConstantExpression)exprProp.GetValue(firstNameObj);

此处,exprObj将正确为ConstantExpression,其值为"It worked!"