与表达式树设置字段值 [英] Set field value with Expression tree

查看:115
本文介绍了与表达式树设置字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个类的所有字段的表达式。
所以我采用的这个帖子以我的需求:

I need to create an expression for all fields in a class. So I've adopted this post to my needs:

public static void Sample()
{
    var setters = GetFieldSetterExpressions<Account>();
    var myAccount = new Account();
    setters["AccounHolder"](myAccount, "Giovanni");
    setters["Pin"](myAccount, 123);
}

public static Dictionary<string, Action<T, object>> GetFieldSetterExpressions<T>() where T: class 
{

    var dic = new Dictionary<string,Action<T,object>>();

    var type = typeof(T);
    var fields = type.GetFields();
    foreach (var fieldInfo in fields)
    {
        Type fieldType;

        if (IsNullableType(fieldInfo.FieldType))
            fieldType = Nullable.GetUnderlyingType(fieldInfo.FieldType);
        else
            fieldType = fieldInfo.FieldType;


        ParameterExpression targetExp = Expression.Parameter(type, "target");
        ParameterExpression valueExp = Expression.Parameter(fieldType, "value");

        MemberExpression fieldExp = Expression.Field(targetExp, fieldInfo);
        BinaryExpression assingExp = Expression.Assign(fieldExp, valueExp);

        var setter = Expression.Lambda<Action<T, object>>(assingExp, targetExp, valueExp).Compile();

        dic.Add(fieldInfo.Name, setter);
    }

    return dic;
}



我的问题是 Expression.Lambda<作用<吨,对象>>(..),因为本场可例如字符串,我得到一个exeption。
我试图intregrate Expression.Convert 在我的片段,但无法弄清楚如何实现它。

My problem is Expression.Lambda<Action<T,object>>(..) since the field can be for example string, I get an exeption. I've tried to intregrate Expression.Convert in my snippet, but couldn't figure out how to implement it.

如何我需要在我的代码转换部分集成的?

How do I need to integrate the conversion part in my code?

推荐答案

表达<作用< T,对象>> 表示第二个参数的类型应为的对象,而你的代码使用属性类型。这是应该的:

Expression<Action<T, object>> means that the second parameter is expected to be of type object, while your code is using propertyType. Here is how it should be:

var type = typeof(T);
var fields = type.GetFields();
foreach (var fieldInfo in fields)
{
    var targetExp = Expression.Parameter(type, "target");
    var valueExp = Expression.Parameter(typeof(object), "value");

    var fieldExp = Expression.Field(targetExp, fieldInfo);
    var assignExp = Expression.Assign(fieldExp, Expression.Convert(valueExp, fieldExp.Type));

    var setter = Expression.Lambda<Action<T, object>>(assignExp, targetExp, valueExp).Compile();

}

这篇关于与表达式树设置字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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