行动代表。如何获取调用该方法的实例
Posted
技术标签:
【中文标题】行动代表。如何获取调用该方法的实例【英文标题】:Action delegate. How to get the instance that call the method 【发布时间】:2011-07-21 13:01:06 【问题描述】:我有一个动作,我想知道如何访问调用该方法的实例。
示例:
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"
谢谢
【问题讨论】:
【参考方案1】:我认为您正在寻找 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);
请注意,这非常脆弱 - 但它应该适用于简单的情况。
【讨论】:
不,Delegate.Target 是调用动作的类。我想要调用该方法的实例。 @Jean 在那种情况下,我不明白你在追求什么。请提供一个简短但完整的示例 @Jean:这对您不起作用的原因是您将方法调用包装在一个相当无用的 lambda 中。试试FindInstance(InstanceOfAClass.Method)
(没有 lambda),它会按照你的意愿工作。如果您希望它使用 lambda 语法,则需要接受 Expression<Action>
类型的参数并遍历表达式树。
我试过这个表达式。但它只给我关于调用的信息,而不是关于值(实例)的信息
@Jean-Philippe:表达式树是前进的方向。现在想出一个例子......【参考方案2】:
其实我不知道你是否可以这样做。 Delegate
类仅包含两个属性:Target
和 Method
。访问Target
将不起作用,因为您正在创建一个新的匿名方法,因此该属性将返回调用FindInstance
方法的类。
试试这样的方法:
FindInstance(this.MyInstance.DoSomething);
然后访问Target
属性如下:
public void FindInstance(Action action)
dynamic instance = action.Target;
Console.WriteLine(instance.Property1);
【讨论】:
对不起,目标不是实例,而是关于实例的信息。以上是关于行动代表。如何获取调用该方法的实例的主要内容,如果未能解决你的问题,请参考以下文章
如何在对方法 onDestinationChanged() 的调用中获取选定的 Fragment 实例