I have this lambda expression Expression<Func<bool>> commandToExecute
Then I pass an instance of a class in there with a method:
_commandExecuter.ProcessCommand (() => aClass.Method())
How do I get the instance of aClass within the ProcessCommand method?
I want to execute some addiontal methods of this class or get some property values.
Is this possible?
EDIT:
I now have written a simple static helper method to get the instance:
private static object GetReferredProviderInstance(Expression body)
{
var methodCallExpression = body as MethodCallExpression;
if (methodCallExpression != null)
{
var constantExpression = methodCallExpression.Object as ConstantExpression;
if (constantExpression != null) return constantExpression.Value;
}
return null;
}
The method call looks like this …
Expression body = commandToExecute.Body; // this is the method parameter Expression<Func<bool>> commandToExecute
var referredProviderInstance = GetReferredProviderInstance(body);
The problem here is, that the cast to the ConstantExpression results into Null. So the constantExpression is always null.
Any ideas?
EDIT 2
I fixed the problem …
private static object GetReferredProviderInstance(Expression body)
{
var methodCallExpression = body as MethodCallExpression;
if (methodCallExpression != null)
{
var memberExpression = methodCallExpression.Object as MemberExpression;
if (memberExpression != null)
{
var constantExpression = memberExpression.Expression as ConstantExpression;
if (constantExpression != null) return constantExpression.Value;
}
}
return null;
}
But here comes a new problem. I only get the instance of the windows form where the reffered instance of my provider is located.
How do I get the real object (aClass) of the lambda expression?
This is actually possible but it depends on what you pass into this method. Suppose you have the scenario where you pass an instance method of the class that you are in to
ProcessCommand:Then you can use the following
ProcessCommandmethod. This only works becauseMethodToCallis called on this instance.The more complicated scenario is as follows:
The method we are calling is now in another class and isn’t called on this instance but on an instance of
CalledClasscalledcalledClass. But how does the compiler pass thecalledClassvariable into the lambda expression? There is nothing that defines a fieldcalledClassthat the methodMethodToCallcan be called on.The compiler solves this by generating an inner class with one field with the name
calledClass. As a result theProcessCommandmethod now becomes this:Slightly more complicated because the compiler has to generate an anonymous inner class.