行动代表.如何获取调用该方法的实例

Jea*_*erc 10 c# delegates action

我有一个Action,我想知道如何访问调用该方法的实例.

例:

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"
    }
Run Code Online (Sandbox Code Playgroud)

谢谢

Jon*_*eet 8

我想你正在找房子Delegate.Target.

编辑:好的,现在我看到你所追求的是什么,你需要一个表达动作的表达式树.然后你可以找到方法调用的目标作为另一个表达式树,从中构建一个LambdaExpression,编译并执行它,并查看结果:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这非常脆弱 - 但它应该在简单的情况下工作.