I have a program that attaches a listener to an object every time the window switches, and then calls a delegate when an event occurs on this window.
The problem is that the code assigns a new delegate every time a window is switched to, meaning one window could have multiple delegates called for one event.
To prevent this I would like to be able to un register a delegate from within the delegate function.
For example:
void OnWindowChange(CustomClass newWindow){
newWindow.OnEvent += delegate {
Console.WriteLine("This event happened.");
newWindow.OnEvent -= *this delegate*;
};
}
I was considering not using an anonymous function, but the problem is, there are at least 10 events per window object that all need hooked. So anonymous seems to be the best (DRYist) way.
If there is a better way to go about doing this, I am open to it.