从字符串构造嵌套属性的 LambdaExpression [英] Construct LambdaExpression for nested property from string

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

问题描述

我试图在运行时根据属性名称为嵌套属性创建 lambda 表达式.基本上我试图创建指定的 lambda 表达式:

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

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

However all I am given is the type of Foo and the string "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);
}

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

However this code does not work for nested properties and I'm not sure how to create the LambdaExpression to do the work of 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
}

?

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

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