c# Expression Lambda 从字符串到 Func<T>

标签 c# linq expression

我尝试从字符串实现动态 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.Lambda 两次,本质上是将一个函数包装到另一个函数中。试试这个:

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# Expression Lambda 从字符串到 Func<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42204753/

相关文章:

c# webbrowser 显示你想要的

c# - MarshalByRefType

c# - 对象内对象的 Entity Framework LINQ 表达式

c# - Expression 和 Delegate 之间的转换错误

c# - 如何在 texture2D Unity3D 上绘制矩形

c# - 为什么 Linq Cast<> 助手不能与隐式转换运算符一起使用?

c# - 使用 Linq 和 C#,是否可以加入两个列表但在每个项目处交错?

c# - Linq-to-Entities/Linq-to-SQL,哪种数据轮询方式更高效?

c - 表达式必须是可修改的值 (C)

c# - kentico 无法修剪字符串,错误 outOfBoundException