构建LambdaEx pression从字符串嵌套属性 [英] Construct LambdaExpression for nested property from string

查看:141
本文介绍了构建LambdaEx pression从字符串嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个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
}

这篇关于构建LambdaEx pression从字符串嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆