Reputation: 1603
A user is passing me a string with a class name and another string with a field from that class that I'm supposed to use to extract some information with. Here are a couple of sample classes; they all inherit from the same base class:
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;
}
}
The user will give me something like 'PersonRow' and 'FirstName', from which I need to dive into the FirstName
field and extract the value of a member in it called Expression
.
I'll spare the details of what Int32Field
and StringField
are doing internally, but suffice it to say both these types have an Expression
member which is a string I need to use.
I'm trying to use reflection to do this, and have gotten this far:
var myClassType = Type.GetType("PersonRow");
var myFields = myClassType.GetField("Fields", BindingFlags.Public | BindingFlags.Static);
var fieldListing = myFields.GetValue(null);
...at this point fieldListing
is an object which, underneath the hood, is of type PersonRow.RowFields
. However I'm kind of stuck in going past this, in that I'm not sure how to enumerate over that array and extract the Expression
value from the field I'm interested in?
Upvotes: 0
Views: 43
Reputation: 27377
I've slightly modified and stubbed out what appears to be your model, and ended up with this:
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; }
}
Now, essentially we're looking for the value of PersonRow.Fields.FirstName.expr
, which can be done with the following code:
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);
Here, exprObj
will correctly be a ConstantExpression
with the value "It worked!"
Upvotes: 1