加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:56:31 所属栏目:百科 来源:网络整理
导读:我试着用表达树玩一下. 我有一个List string的对象我想构建一个表达式树,为这个属性添加一个值,但我想指定要通过Func添加的值. 目前我试试这个…… public static ActionT CreateMethodAddObjectToListT,C(this Type type,string property,FuncC ctorFunctio
我试着用表达树玩一下.
我有一个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,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,valueExpr);

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

    return function;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读