Assign Property with an ExpressionTree

前端 未结 4 651
伪装坚强ぢ
伪装坚强ぢ 2020-12-17 17:01

I\'m playing around with the idea of passing a property assignment to a method as an expression tree. The method would Invoke the expression so that the property gets assig

4条回答
  •  忘掉有多难
    2020-12-17 17:23

    You can't do it this way. First, lambda expressions can be converted only to delegate types or Expression.

    If you change the signature of the method (for now ignoring its implementation) to public void RunAndRaise(Expression Exp), the compiler complains that “An expression tree may not contain an assignment operator”.

    You could do it by specifying the property using lambda and the value you want to set it to in another parameter. Also, I didn't figure out a way to access the value of vm from the expression, so you have to put that in another parameter (you can't use this for that, because you need the proper inherited type in the expression):see edit

    public static void SetAndRaise(
        TViewModel vm, Expression> exp, TProperty value)
        where TViewModel : ViewModelBase
    {
        var propertyInfo = (PropertyInfo)((MemberExpression)exp.Body).Member;
        propertyInfo.SetValue(vm, value, null);
        vm.PropertyChanged(propertyInfo.Name);
    }
    

    Another possibility (and one I like more) is to raise the event from setter specifically using lambda like this:

    private int m_value;
    public int Value
    {
        get { return m_value; }
        set
        {
            m_value = value;
            RaisePropertyChanged(this, vm => vm.Value);
        }
    }
    
    static void RaisePropertyChanged(
        TViewModel vm, Expression> exp)
        where TViewModel : ViewModelBase
    {
        var propertyInfo = (PropertyInfo)((MemberExpression)exp.Body).Member;
        vm.PropertyChanged(propertyInfo.Name);
    }
    

    This way, you can use the properties as usual, and you could also raise events for computed properties, if you had them.

    EDIT: While reading through Matt Warren's series about implementing IQueryable, I realized I can access the referenced value, which simplifies the usage of RaisePropertyChanged() (although it won't help much with your SetAndRaise()):

    private int m_value;
    public int Value
    {
        get { return m_value; }
        set
        {
            m_value = value;
            RaisePropertyChanged(() => Value);
        }
    }
    
    static void RaisePropertyChanged(Expression> exp)
    {
        var body = (MemberExpression)exp.Body;
        var propertyInfo = (PropertyInfo)body.Member;
        var vm = (ViewModelBase)((ConstantExpression)body.Expression).Value;
        vm.PropertyChanged(vm, new PropertyChangedEventArgs(propertyInfo.Name));
    }
    

提交回复
热议问题