yangyukun
yangyukun
采纳率100%
2016-07-10 03:11 阅读 2.2k
已采纳

c# 关于构建表达式树的问题

Expression> ex = (ins, param) => ((Program)ins).Call(param[0], param[1], param[2]);

有以上表达式,如何构建该表达式树?
通过Expression Tree Visualizer看到表达式结构是这样的图片说明但不知道如何构建表达式树,希望高手能指导一下,我自己构建了一段:ParameterExpression px = Expression.Parameter(typeof(object[]), "argus");

        ConstantExpression index1 = Expression.Constant(0);
        ConstantExpression index2 = Expression.Constant(1);
        ConstantExpression index3 = Expression.Constant(1);

        BinaryExpression pm1 = Expression.ArrayIndex(px, index1);
        BinaryExpression pm2 = Expression.ArrayIndex(px, index2);
        BinaryExpression pm3 = Expression.ArrayIndex(px, index3);

后面构建主体的时候就不太清楚了,谢谢赐教

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    caozhy 从今以后生命中的每一秒都属于我爱的人 2016-07-10 04:20
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            public void Call(object a, object b, object c)
            {
                Console.WriteLine(a);
                Console.WriteLine(b);
                Console.WriteLine(c);
            }
            static void Main(string[] args)
            {
                //Expression<Action<object, object[]>> ex = (ins, param) => ((Program)ins).Call(param[0], param[1], param[2]);
                ParameterExpression ins = Expression.Parameter(typeof(object), "ins");
                ParameterExpression param = Expression.Parameter(typeof(object[]), "param");
                ConstantExpression index1 = Expression.Constant(0);
                ConstantExpression index2 = Expression.Constant(1);
                ConstantExpression index3 = Expression.Constant(2);
                BinaryExpression pm1 = Expression.ArrayIndex(param, index1);
                BinaryExpression pm2 = Expression.ArrayIndex(param, index2);
                BinaryExpression pm3 = Expression.ArrayIndex(param, index3);
                UnaryExpression p = Expression.TypeAs(ins, typeof(Program));
                MethodCallExpression call = Expression.Call(p, typeof(Program).GetMethod("Call"), pm1, pm2, pm3);
                Expression<Action<object, object[]>> ex = Expression.Lambda<Action<object, object[]>>(call, ins, param);
                ex.Compile()(new Program(), new object[] { 1, 2, 3 });
            }
        }
    }
    
    
    点赞 2 评论 复制链接分享
  • yangyukun yangyukun 2016-07-10 05:43

    非常非常感谢您的回答

    点赞 评论 复制链接分享

相关推荐