c# - How can i capture local variable in dynamic method? -
this question has answer here:
- local variable , expression trees 2 answers
- issue closure variable capture in c# expression 2 answers
(i'm new english)
i use expression.lambda dynamically creating lambda.
i want capture variables don't know how 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); // } /** skip */ }
i want create lambda(look comment "this") using expression@lambda. it's possible?
this code i'm trying 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
Comments
Post a Comment