lundi 21 mai 2018

Set Object Property of Object Property by Reflection

I used this SO Question to retrieve a property of an object using reflection. The property I retrieved is another object that has a property called Value that I need to access. All of the potential objects that I retrieve using reflection derive from the same class EntityField and therefore all have a Value property. I saw this SO question that hinted at how I might be able to access the Value property, but I couldn't quite put together the correct code. How can I access the Value property on an object retrieved by reflection?

Main

private static void SetValues(JObject obj, EntityBase entity)
{
    // entity.GetType().GetProperty("Property") returns an EntityField Object
    // I need to set EntityField.Value = obj["Value"] 
    // Current code sets EntityField = obj["Value"] which throws an error
    entity.GetType().GetProperty("Property").SetValue(entity, obj["Value"], null);
}

EntityField

public class EntityField<T> : EntityFieldBase
{
    private Field _Field;
    private T _Value;

    public EntityField(Field field, T value){
        this._Field = field;
        this._Value = value;
    }

    public Field Field
    {
        get
        {
            return this._Field;
        }
        set
        {
            if (this._Field != value)
            {
                this._Field = value;
            }
        }
    }

    public T Value
    {
        get
        {
            return this._Value;
        }
        set
        {
            if (!EqualityComparer<T>.Default.Equals(this._Value, value))
            {
                this._Value = value;
                this._IsDirty = true;
            }
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire