I have this method:
public override void respond(params string[] resargs)
{
foreach (command cmd in pndgcmds)
{
cmd(this);
}
if (objs[resargs[0]].status)
objs[resargs[0]].request(resargs);
else
{
pndgcmds.Add(
(myclass master) =>
{
if (master.objs[resargs[0]].status != true) return;
master.objs[resargs[0]].request(resargs);
//code to remove the delegate
});
}
}
which checks if an object is able to respond, makes it respond if it does, otherwise stores the command in a dictionary so that the status is checked and called the next time a respond is called.
I have two questions.
-
How do I write code to remove the delegate? I have no idea how to do that.
-
As you can see, much of the inner workings of the delegate relies on method parameters. How will the delegate behave?
Thanks in advance!
Anonymous methods are a pain to remove, as the instance of the captire-context is only available when creating it, an is required. Fortunately, there’s a trick:
This is now a self-unsubscribing handler, that will unsubscribe itself when invoked. Note that to do this we need to store the delegate instance (
handler), but we then create a closure over that variable. The initial=nullis a requirement of definite assignment.You should note that the
resargsvariable is also captured, and this could lead to confusion if the value at index-zero changes after subscription but before it is invoked. If you want to use the value “now”, then close over that instead: