我尝试从字符串实现 e 动态 Funx 表达式

Expression<Func<CustomerDto, object>> expr = (src) => src.Customer.Id;
Func<CustomerDto, object> delg = expr.Compile();
var id = delg.Invoke(customerListDtos[0]);

并返回 id (es. 123)

所以现在我尝试从字符串创建表达式
    public Expression<Func<T, object>> GetLambda<T>(string property)
    {

        var param = Expression.Parameter(typeof(T), "p");
        Expression body = param;
        foreach (var member in property.Split('.'))
        {
            body = Expression.PropertyOrField(body, member);
        }
        //return Expression.Lambda(body, param);

        //Expression parent = Expression.Property(param, property);
        Expression parent = Expression.Lambda(body, param);
        //if (!parent.Type.IsValueType)
        //{
        //    return Expression.Lambda<Func<T, object>>(parent, param);
        //}
        var convert = Expression.Convert(parent, typeof(object));
        return Expression.Lambda<Func<T, object>>(convert, param);
    }

因此,如果我从 GetLambda 调用结果,则输出不是 123,而是
 var data = GetLambda<CustomerDto>("Customer.Id");
 Func<CustomerDto, object> g = data.Compile();
 var id = g(customerListDtos[0]);

结果是
{Method = {Int64 lambda_method(System.Runtime.CompilerServices.Closure, ef.Customer.CustomerDto)}}

最佳答案

您正在调用 Expression.Labmda 两次,实质上是将一个 func 包装到另一个中。试试这个:

public static Expression<Func<T, object>> GetLambda<T>(string property) {
    var param = Expression.Parameter(typeof(T), "p");
    Expression body = param;
    foreach (var member in property.Split('.')) {
        body = Expression.PropertyOrField(body, member);
    }
    var convert = Expression.Convert(body, typeof(object));
    return (Expression<Func<T, object>>) Expression.Lambda(convert, param);
}

关于c#从字符串到Func<T>的表达式Lambda,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42204753/

10-17 01:42