Action委托。如何获得调用方法的实例 [英] Action delegate. How to get the instance that call the method

查看:181
本文介绍了Action委托。如何获得调用方法的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动作,我不知道我怎么能访问调用方法的实例

I have an Action and I wonder how could I access the instance that call the method.

例:

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

推荐答案

我认为你正在寻找的的 Delegate.Target 属性。

I think you're looking for the Delegate.Target property.

编辑:好的,现在我看到你以后,你需要代表动作表达式树。然后,你可以找到方法调用另一个表达式树的目标,搭建起一个LambdaExpression,编译并执行它,并查看结果:

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.

这篇关于Action委托。如何获得调用方法的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆