How do I create a generic Expression that has an expression as a parameter

前端 未结 4 1911
死守一世寂寞
死守一世寂寞 2021-01-06 18:32

There is a DisplayNameFor(x=>x.Title) helper in ASP.Net MVC. I want to implement something similar in behavior.

I want to have a method that accepts

4条回答
  •  太阳男子
    2021-01-06 19:12

    something like this:

    Expression> GenerateAssignExpression
        (Expression> getExpression,
        TProperty Value)
    {
        var getExpressionBody = getExpression.Body as MemberExpression;
        if (getExpressionBody == null)
        {
            throw new Exception("getExpressionBody is not MemberExpression: " + 
                    getExpression.Body);
        }
    
        var objectParameter = (ParameterExpression)getExpression.Parameters[0];
        ConstantExpression constant = Expression.Constant(Value, typeof(TProperty));
        var expAssign = Expression.Assign(e.Body, constant);
    
        return Expression.Lambda>(expAssign, 
                objectParameter, 
                valueParameter);
    }
    

提交回复
热议问题