Action _captureAction;
private void TestSimpleCapturedAction()
{
Action action = new Action(delegate { });
Action printAction =() => Console.WriteLine("Printing...");
action += printAction;
CaptureActionFromParam(action);
action -= printAction;
_captureAction(); //printAction will be called!
}
private void CaptureActionFromParam(Action action)
{
_captureAction =() => action();
}
原因printAction将_captureAction被称为是该行
action -= printAction;
其实翻译成
action = (Action) Delegate.Remove(action, printAction);
这样的动作被抓获CaptureActionFromParam()中的_captureAction不会更改 - 只有TestSimp中的本地'action'变量leCapturedAction()受到影响。
在这种情况下,我希望的行为是printAction不被调用。我能想到的唯一的办法就是defning一个新的“委托容器”级这样:
class ActionContainer
{
public Action Action = new Action(delegate { });
}
private void TestCapturedActionContainer()
{
var actionContainer = new ActionContainer();
Action printAction =() => Console.WriteLine("Printing...");
actionContainer.Action += printAction;
CaptureInvoker(actionContainer);
actionContainer.Action -= printAction;
_captureAction();
}
private void CaptureInvoker(ActionContainer actionContainer)
{
_captureAction =() => actionContainer.Action();
}
这工作,但我不知道是否可以在不引入抽象的这个新层来实现我所期望的行为。实施战略模式很容易导致这种情况,所以人们会认为这种语言和/或BCL会以某种方式在本地支持它。
谢谢!
哇,这个人自己答案!我实际上意识到你的观点,这就是为什么我提出上面的“可变动作”类解决方案(MutalbeAction比ActionContainer更好的名称),但CaptureActionFromParam((=)action>)更加优雅。谢谢 ! – 2010-02-20 18:43:54