Action delegate. How to get the instance that call the method
action, c#, delegates
Solution
I think you're looking for the `Delegate.Target` property.
EDIT: Okay, now I see what you're after, and you need an expression tree representing the action. Then you can find the target of the method call as another expression tree, build a LambdaExpression from that, compile and execute it, and see the result:
using System;
using System.Linq.Expressions;
class Test
{
static string someValue;
static void Main()
{
someValue = "target value";
DisplayCallTarget(() => someValue.Replace("x", "y"));
}
static void DisplayCallTarget(Expression<Action> action)
{
// TODO: *Lots* of validation
MethodCallExpression call = (MethodCallExpression) action.Body;
LambdaExpression targetOnly = Expression.Lambda(call.Object, null);
Delegate compiled = targetOnly.Compile();
object result = compiled.DynamicInvoke(null);
Console.WriteLine(result);
}
}
Note that this is incredibly brittle - but it should work in simple cases.
Problem
I have an Action and I wonder how could I access the instance that call the method. Exemple: ``` this.FindInstance(() => this.InstanceOfAClass.Method()); this.FindInstance(() => this.InstanceOfAClass2.Method()); this.FindInstance(() => this.InstanceOfAClass3.Method()); public void FindInstance(Action action) { // The action is this.InstanceOfAClass.Method(); and I want to get the "Instance" // from "action" } ``` Thank you