行动代表如何获取调用该方法的实例 [英] Action delegate. How to get the instance that call the method
本文介绍了行动代表如何获取调用该方法的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个动作,我想知道如何访问调用该方法的实例。
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"
}
获取Instance
//
谢谢
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.
这篇关于行动代表如何获取调用该方法的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文