I’m a newbie when it comes to expression trees, so I’m not sure how to ask this question or what terminology to use. Here’s an overly-simplifed version of what I’m trying to do:
Bar bar = new Bar();
Zap(() => bar.Foo);
public static void Zap<T>(Expression<Func<T>> source)
{
// HELP HERE:
// I want to get the bar instance and call bar.Zim() or some other method.
}
How can I get to bar inside the Zap method?
Since the expression passed into your
Zapmethod is a tree, you just need to walk the tree using an Expression Tree Visitor and look for the firstConstantExpressionin the expression. It will likely be in the following sequence:Note that the
barinstance is captured by a closure, which is implemented as an internal class with the instance as a member, which is where the 2nd MemberExpression comes from.EDIT
Then you have to get the field from the generated closure like so: