lundi 29 juin 2015

Property not set with reflection

I've came across this strange situation. I have the following model :

public class MyClass
{
    public MyClass(AnotherClassBase myProp)
    {
        MyProp = myProp;
    }

            private AnotherClassBase _MyProp;
    public virtual AnotherClassBase MyProp 
    {
        get
        {
            return _MyProp;
        }
        set
        {
            _MyProp = value;
            DoStuff();
        }
    }
}

I initially instantiate it using the constructor :

 var myInstance = new MyClass(new AnotherClassConcrete1());

And then try to change the property value with some instance of the type AnotherClassConcrete2 using this extension method :

public static void Set<T>(this T target, Expression<Func<T, object>> memberLamda, object value)
    {
        var memberSelectorExpression = memberLamda.Body as MemberExpression;
        if (memberSelectorExpression != null)
        {
            var property = memberSelectorExpression.Member as PropertyInfo;
            if (property != null)
            {
                property.SetValue(target, value, null);
            }
        }
    }

In the debugger inspector, I can see that the value is correctly changed. However, the following returns false :

myInstance.MyProp is AnotherClassConcrete2

And the following returns true :

myInstance.MyProp is AnotherClassConcrete1

Why is that ? And how can I fix that ?





Aucun commentaire:

Enregistrer un commentaire