First of all, sorry for bad title as I don't know many correct terms in C#. I found working 'self-unsubscribing' delegate from here. This code below works (at least for me).
private delegate void V;
private V delVoid;
private void SelfUnsubscribeDelVoid()
{
void Unsubscriber()
{
// Some operation
delVoid -= Unsubscriber;
}
DelVoid += Unsubscriber;
}
However, as I use many 'self-unsubscribing' delegates, there will be a lot variation of SelfUnsubscribeDelVoid()
, each handle different delegates. Therefore, I make one static function with delegate as input parameter. This way, I don't have to make many similar functions. Here's what I come up with.
public static class Delegates
{
public delegate void V();
public static void SelfUnsubscribeDelVoid(V theDelegate, V functionToExecute)
{
void Unsubscriber()
{
functionToExecute();
theDelegate -= Unsubscriber;
}
theDelegate += Unsubscriber;
}
}
public class Caller
{
private Delegates.V OnDoingSomething;
public void FunctionA()
{
Delegates.SelfUnsubscribeDelVoid(OnDoingSomething, FunctionB);
OnDoingSomething(); // FunctionB is not invoked
}
private void FunctionB()
{
// do something
}
}
Unfortunately, my code doesn't work. A bit of try and error raise a likelihood that the onDoingSomething
delegate is not 'linked' with the input theDelegate
, as if they are two different delegates.
Are there mistakes in my code? Is my approach incorrect? Or is what I want simply impossible to do?
Thanks in advance :)
Edit sample code should've followed common naming convention.