49

我试图在运行时根据属性的名称为嵌套属性创建一个 lambda 表达式。基本上我正在尝试创建由以下指定的 lambda 表达式:

var expression = CreateExpression<Foo, object>(foo => foo.myBar.name);

private static Expression CreateExpression<TEntity, TReturn>(Expression<Func<TEntity, TReturn>> expression)
{
    return (expression as Expression);
}

随着课程:

class Foo
{
    public Bar myBar { get; set; }
}
class Bar
{
    public string name { get; set; }
}

但是我得到的只是类型Foo和字符串"myBar.name"

如果它是一个普通属性,例如只需要该值,"myBar"那么我可以使用以下内容:

private static LambdaExpression GetPropertyAccessLambda(Type type, string propertyName)
{
    ParameterExpression odataItParameter = Expression.Parameter(type, "$it");
    MemberExpression propertyAccess = Expression.Property(odataItParameter, propertyName);
    return Expression.Lambda(propertyAccess, odataItParameter);
}

但是,此代码不适用于嵌套属性,我不确定如何创建 LambdaExpression 来完成foo.myBar.name.

我认为这将是这样的:

GetExpression(Expression.Call(GetExpression(Foo, "myBar"), "name"))

但我似乎无法弄清楚如何让它全部工作,或者是否有更好的方法在运行时做到这一点。

4

2 回答 2

128

你的意思是:

static LambdaExpression CreateExpression(Type type, string propertyName) {
    var param = Expression.Parameter(type, "x");
    Expression body = param;
    foreach (var member in propertyName.Split('.')) {
        body = Expression.PropertyOrField(body, member);
    }
    return Expression.Lambda(body, param);
}

例如:

class Foo {
    public Bar myBar { get; set; }
}
class Bar {
    public string name { get; set; }
}
static void Main() {
    var expression = CreateExpression(typeof(Foo), "myBar.name");
    // x => x.myBar.name
}

?

于 2013-04-25T07:17:15.390 回答
-1

要构造 lambda 表达式但使用内联解决方案,您可以执行以下操作:

var param = Expression.Parameter(typeOf(FooBar), "x");

// you "concat" your expression here :
var propertyExpression = Expression.PropertyOrField(param, "myBar");
propertyExpression = Expression.PropertyOrField(propertyExpression, "name");
// expected result : "x.myBar.name" as a body expression

var expression = Expression.Lambda(propertyExpression, param);
// x => x.myBar.name
于 2020-10-09T07:23:37.437 回答