考虑
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();
}
_captureAction 将调用 printAction 的原因是该行
action -= printAction;
实际上翻译成
action = (Action) Delegate.Remove(action, printAction);
因此 CaptureActionFromParam() 中 _captureAction 捕获的动作不会改变 - 只有 TestSimpleCapturedAction() 中的本地“动作”变量受到影响。
在这种情况下,我想要的行为是不调用 printAction。我能想到的唯一解决方案是这样定义一个新的“委托容器”类:
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 会以某种方式原生支持它。
谢谢 !