lundi 11 décembre 2017

Reflection and inheritance issue c#

I'm trying to determine the MemberExpression of all the parts of a structure with the use of reflection. These are some of the objects to illustrate the issue:

public class Entity
{
    public Part FirstPart { get; set; }
}

public class Part
{
    public int Id { get; set; }
}

public class SubPart : Part
{
    public int ExtraProperty { get; set; }
}

The function I used to determine the MemberExpression of every component, works fine for the following object structure:

        Entity entity = new Entity() { FirstPart = new Part() { Id = 1 } };

The function is:

        var param = Expression.Parameter(entity.GetType());
        String[] childProperties = ("FirstPart.Id").Split('.');
        var propExpression = Expression.PropertyOrField(param, childProperties[0]);
        for (int i = 1; i < childProperties.Length; i++)
        {
            propExpression = Expression.PropertyOrField(propExpression, childProperties[i]);
        }

But this doesn't work for the following, due to inheritance:

        Entity entity = new Entity() { FirstPart = new SubPart() { ExtraProperty = 1 } };

In order to retrace the properties we need to change the path to "FirstPart.ExtraProperty":

        var param = Expression.Parameter(entity.GetType());
        String[] childProperties = ("FirstPart.ExtraProperty").Split('.');
        var propExpression = Expression.PropertyOrField(param, childProperties[0]);
        for (int i = 1; i < childProperties.Length; i++)
        {
            propExpression = Expression.PropertyOrField(propExpression, childProperties[i]);
        }

The error message states that: 'ExtraProperty' is not a member of Part. Does anyone have an idea how to overcome this issue?





Aucun commentaire:

Enregistrer un commentaire