c# - 对表达式树使用 lambda 返回值

标签 c# lambda expression-trees

我试着玩一下表达式树。 我有一个 List<string> 的对象我想构建一个向该属性添加值的表达式树,但我想通过 Func 指定要添加的值. 目前我正在尝试这个...

public static Action<T> CreateMethodAddObjectToList<T, C>(this Type type, string property, Func<C> ctorFunction)
        {
            PropertyInfo fieldInfo = type.GetProperty(property);

            if (fieldInfo == null)
            {
                return null;
            }

            ParameterExpression targetExp = Expression.Parameter(type, "target");
            MemberExpression fieldExp = Expression.Property(targetExp, property);
            var method = fieldExp.Type.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);

            Expression<Func<C>> ctorExpression = () => ctorFunction();

// but this doesnt work because I can't use the ctorExpression in this way
            var callExp = Expression.Call(fieldExp, method, ctorExpression);

            var function = Expression.Lambda<Action<T>>(callExp, targetExp).Compile();

            return function;
        }

电话看起来像

var dummyObject = new DummyObject { IntProperty = 5 };

            Action<DummyObject> setter = typeof (DummyObject).CreateMethodAddObjectToList<DummyObject, string>("StringList", () => "Test" );

最佳答案

您可以将 ctorFunction 更改为 Expression<Func<C>>然后在生成的操作中调用它:

public static Action<T> CreateMethodAddObjectToList<T, C>(this Type type, string property, Expression<Func<C>> createExpr)
{
    PropertyInfo fieldInfo = type.GetProperty(property);

    if (fieldInfo == null)
    {
        return null;
    }

    ParameterExpression targetExp = Expression.Parameter(type, "target");
    MemberExpression fieldExp = Expression.Property(targetExp, property);
    var method = fieldExp.Type.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);

    var valueExpr = Expression.Invoke(createExpr);
    var callExpr = Expression.Call(fieldExp, method, valueExpr);

    var function = Expression.Lambda<Action<T>>(callExpr, targetExp).Compile();

    return function;
}

关于c# - 对表达式树使用 lambda 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008016/

相关文章:

c# - SQLite 和 .NET 用户控件

C#写入文件问题

c# - 使用 Process Class c# 列出进程内存和 CPU 使用情况时出现问题

c# - Lambda 表达式 - C# 编译器推理

.net - 转换和拆箱有什么区别?

c# - 从服务器端的路由值解析 url

Python:使用 pandas.pivot_table 展平事件日志并显示执行事件所花费的时间

c# - 如何使用 lambda 表达式和 linq 从范围中获取元素?

c# - Lambda 到表达式树的转换

c# - 如何通过现有对象上的表达式树调用构造函数?