検討
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によってキャプチャされたアクションは変更されません。つまり、TestSimpleCapturedAction()のローカルの「action」変数のみが影響を受けます。
このようなシナリオでの私の望ましい動作は、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が何らかの形でネイティブにサポートしたりします。
ありがとう !