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个回答

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 });
        }
    }
}

非常非常感谢您的回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐