Expression Trees and Invoking a Delegate

前端 未结 4 1201
余生分开走
余生分开走 2020-12-15 06:10

So I have a delegate which points to some function which I don\'t actually know about when I first create the delegate object. The object is set to

4条回答
  •  醉酒成梦
    2020-12-15 06:55

    I think what you want to do is use the Target and Method properties of the delegate to pass to create a Call expression. Building on JulianR's sample, this is what it would look like:

    Action func = i => Console.WriteLine(i * i);
    
    var callExpr = Expression.Call(Expression.Constant(func.Target), func.Method, Expression.Constant(5));
    
    var lambdaExpr = Expression.Lambda(callExpr);
    var fn = lambdaExpr.Compile();
    fn();    //  Prints 25
    

提交回复
热议问题