lundi 18 avril 2016

How to assign the value returned by Expression.Call() to a ParameterExpression?

I have the following code :

var factory = Expression.Parameter(typeof(FooFactory));
var fooInstance = Expression.Variable(typeof(Foo));

var factoryCall = Expression.Call(factory, "Instantiate", new[] { typeof(Foo) });
Expression.Assign(fooInstance, factoryCall); 

List<Expression> expressions = new List<Expression>();
// TODO : add more expressions to do things on fooInstance ...//

expressions.Add(fooInstance); //return fooInstance
Expression finalExpr = Expression.Block(new[] { fooInstance }, expressions);

What it is supposed to do :

  1. Use factory given as parameter and call Instantiate<T>() method on it.
  2. Store the returned value (a foo instance) to a local variable.
  3. Do things on that local variable (missing in that example)
  4. Return the instance

The problem is : when I compile and call the expression, Instantiate() is never called. The value returned is always null :

var method = Expression.Lambda<Func<FooFactory, Foo>>(finalExpr, factory).Compile();
Foo foo = method(new FooFactory());  //foo is null :(





Aucun commentaire:

Enregistrer un commentaire