构建LambdaEx pression从字符串嵌套属性嵌套、字符串、属性、LambdaEx

2023-09-02 21:45:01 作者:╭能忘了情╯

我想创建一个lambda EX pression嵌套属性在运行时从PROPERT的名称。基本上我想创建由指定的拉姆达EX pression:

I am trying to create a lambda expression for a nested property at run-time from the name of the propert. Basically I am trying to create the lambda expression specified by:

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; }
}

但是,所有我给出的的类型和字符串myBar.name

如果它是一个正常的财产,如只需要值myBar然后我可以使用以下内容:

If it were a normal property such as just needing the value "myBar" then I could use the following:

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);
}

然而,这code没有嵌套性工作,我不知道如何创建LambdaEx pression做 foo.myBar.name 。

我认为这将是这样的:

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

不过,我似乎无法找出如何获得这一切的工作,或是否有更好的方法在运行时做到这一点。

But I can't seem to work out how to get it all working, or if there's a better way to do this at run-time.

推荐答案

你的意思是:

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
}