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 :
- Use factory given as parameter and call
Instantiate<T>()
method on it. - Store the returned value (a foo instance) to a local variable.
- Do things on that local variable (missing in that example)
- 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