获得行动目标

Ben*_*ual 6 .net c# anonymous-methods .net-4.0

我创建了以下示例代码:

class Program {
    static void Main(string[] args) {
        var x = new ActionTestClass();
        x.ActionTest();
        var y = x.Act.Target;
    }
}

public class ActionTestClass {
    public Action Act;
    public void ActionTest() {
        this.Act = new Action(this.ActionMethod);
    }

    private void ActionMethod() {
        MessageBox.Show("This is a test.");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我以这种方式执行此操作时,y将是ActionTestClass类型的对象(为x创建).现在,当我改变线

this.Act = new Action(this.ActionMethod);
Run Code Online (Sandbox Code Playgroud)

this.Act = new Action(() => MessageBox.Show("This is a test."));
Run Code Online (Sandbox Code Playgroud)

y(行动目标)将为空.有没有办法,我可以在使用匿名操作的方式上获取Target(在示例中为ActionTestClass对象)?

lep*_*pie 1

缺少Target(iow == null) 意味着委托要么正在调用static方法,要么没有捕获任何环境(iow 不是闭包,只是一个“函数指针”)。