How can i capture local variable in dynamic method?

335 views Asked by At

(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 <Context, object> 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
0

There are 0 answers