How to convert the expression <Func <T, TProperty >> to the expression <Func <T, TNewProperty >>

The following works, but my Body.NodeType changes to Convert instead of MemberAccess, which is a problem when getting ModelMetadata.FromLambdaExpression:

private Expression<Func<TModel, TNewProperty>> ConvertExpression<TProperty, TNewProperty>(Expression<Func<TModel, TProperty>> expression)
{
    Exression converted = Expression.Convert(expression.Body, typeof(TNewProperty));
    var result =  Expression.Lambda<Func<TModel, TNewProperty>>(converted,    expression.Parameters);
    return result;
}

In the context of ASP.NET MVC 2.0, I have my own editor for:

public MvcHtmlString EditorFor<TProperty>(Expression<Func<TModel, TProperty>> expression)

The EditorFor then delegates the call internally, based on metadata, to specific methods, for example:

public DecimalTextBox DecimalTextBoxFor(Expression<Func<TModel, decimal?>> expression)

DecimalTextBox has a Value property of type decimal ?, so I want to set it:

decimalTextBox.Value(expression.Compile()(ViewData.Model));

Calling the EditorFor form for DecimalTextboxFor does not compile bacause, the types do not match, and so I need a conversion.

, , Expression.Body.NodeType , ModelMetadata.FromLambdaExpression , ArrayIndex, Call, MemberAccess Parameter. .

DecimalTextBoxFor :

public DecimalTextBox DecimalTextBoxFor(Expression<Func<TModel, TProperty>> expression)

:

decimalTextBox.Value((decimal?) Convert.ChangeType(expression.Compile()(ViewData.Model), typeof(decimal?)));

, :

private Expression<Func<TModel, TNewProperty>> ConvertExpression<TProperty, TNewProperty>(Expression<Func<TModel, TProperty>> expression)
{
     Expression<Func<TModel, TNewProperty>> convertedExpression = expression as Expression<Func<TModel, TNewProperty>>;
}

(, single to double) , .

...

+3
1

, NodeType Body. Convert . , , "", .. node .

, , , , , NodeType, . : Body , Body ( , , Convert). , .

+1

Source: https://habr.com/ru/post/1763457/


All Articles