0

(I'm new to english)

I use Expression.Lambda for dynamically creating lambda.

I want capture variables but i don't know how to capture using Expression.



    public class Demo
    {
        /** skip */
        private Context _context;
        public void Route(Person person)
        {
            Packet packet = Packet.GetPacket();
            Func &ltContext, object&gt lambda =
                (context) => this.OtherMethod(context, person, packet); // THIS
        }
        /** skip */
    }

I want create lambda(look comment "THIS") using Expression@Lambda. It's possible?


This is the code I'm trying to make.(Not Work)

    var main = new DemoApplication();
    var mainType = main.GetType();
    var methodInfo = mainType.GetMethod("OtherMethod");
    var targetExpression = Expression.Parameter(mainType, "this");
    var parameterExpressions = methodInfo.GetParameters().Select(info => Expression.Parameter(info.ParameterType, info.ParameterType.Name)).ToArray();
    var body = Expression.Call(targetExpression, methodInfo, parameterExpressions); // {this.OtherMethod(Context, Person, Packet)}
    var lambdaParameters = new List<ParameterExpression> { parameterExpressions[0] };
    var lambda = Expression.Lambda(body, lambdaParameters); // {Context => this.OtherMethod(Context, Person, Packet)}
    var lambdaDelegate = lambda.Compile(); // ERROR
  • Variable capturing is a compiler-generated construct. It just involves generating a hidden class where the variable will live. If you want "capturing" in your expression, you'll have to do the same: declare a class where the variable can live, and then use that variable from an instance of that class, rather than having a local variable. – Peter Duniho Sep 12 '17 at 00:47
  • I solved it, Thanks @PeterDuniho ! – GoodGoodMan Sep 12 '17 at 02:32

0 Answers0