Action委托。如何获得调用方法的实例

编程入门 行业动态 更新时间:2024-10-11 11:18:24
本文介绍了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委托。如何获得调用方法的实例

本文发布于:2023-11-28 17:42:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643348.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何获得   实例   方法   Action

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!