ラムダ式の代わりにクロージャーを自分で実装することで、これを解決する方法があります。
キャプチャ変数として使用するクラスは次のとおりであるとします。
public class A
{
public void DoSomething()
{
...
}
}
public class B
{
public void DoSomething()
{
...
}
}
public class C
{
public void DoSomething()
{
...
}
}
これらのクラスはキャプチャ変数として使用されるため、インスタンス化します。
A a = new A();
B b = new B();
C c = new C();
以下に示すように、クロージャ クラスを実装します。
private class EventHandlerClosure
{
public A a;
public B b;
public C c;
public event EventHandler Finished;
public void MyMethod(object, MyEventArgs args)
{
a.DoSomething();
b.DoSomething();
c.DoSomething();
Console.WriteLine("I did it!");
Finished?.Invoke(this, EventArgs.Empty);
}
}
クロージャー クラスをインスタンス化し、ハンドラーを作成してから、イベントをサブスクライブし、クロージャー クラスの Finished イベントからサブスクライブを解除するラムダ式をサブスクライブします。
var closure = new EventHandlerClosure
{
a = a,
b = b,
c = c
};
var handler = new MyEventHandler(closure.MyMethod);
MyEvent += handler;
closure.Finished += (s, e)
{
MyEvent -= handler;
}