使用表达式动态评估属性字符串 [英] Dynamically evaluating a property string with Expressions

查看:50
本文介绍了使用表达式动态评估属性字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何构建满足以下目标的表达式:

How do I build an expression that will fulfill the following goal:

public object Eval(object rootObj, string propertyString)

例如:Eval(person, "Address.ZipCode") => return person.Address.ZipCode

Expression.PropertyOrField不起作用,因为我没有每个中间属性的类型.我想避免在脚本库上创建依赖项.

Expression.PropertyOrField doesn't work because I don't have the type of each intermediate property. I'd like to avoid creating a dependency on a scripting library.

我想尝试使用表达式,因为它将允许我存储这些表达式树的缓存,因为它们将被执行多次.我知道可以通过反射来迭代或递归执行此操作.

I want to try to use expressions because it would allow me to store a cache of these expression trees as they would be executed several times. I'm aware that it's possible to do this iteratively or recursively with reflection.

推荐答案

听起来您正在寻找这样的东西:

It sounds like you're looking for something like this:

public object Eval(object root, string propertyString)
{
    var propertyNames = propertyString.Split('.');
    foreach(var prop in propertyNames)
    {
        var property = root.GetType().GetProperty(prop);
        if (property == null)
        {
            throw new Exception(...);
        }

        root = property.GetValue(root, null);
    }

    return root;
}

要创建Expression,请使用以下方法:

To create an Expression use this:

public Expression Eval(object root, string propertyString)
{
    var propertyNames = propertyString.Split('.');
    ParameterExpression param = Expression.Parameter(root.GetType, "_");
    Expression property = param;
    foreach(var prop in propertyName)
    {
        property = Expression.PropertyOrField(property, prop);
    }

    return Expression.Lambda(property, param);
}

这篇关于使用表达式动态评估属性字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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