簡體   English   中英

行動代表。如何獲取調用該方法的實例

[英]Action delegate. How to get the instance that call the method

我有一個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"
    }

謝謝

我想你正在尋找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類只包含兩個屬性: TargetMethod 由於您正在創建新的匿名方法,因此訪問Target將無效,因此該屬性將返回調用FindInstance方法的類。

嘗試這樣的事情:

FindInstance(this.MyInstance.DoSomething);

然后按如下方式訪問Target屬性:

public void FindInstance(Action action)
{
    dynamic instance = action.Target;
    Console.WriteLine(instance.Property1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM