public event EventHandler ConstructDesign;
public DataGridView dataGrid = new DataGridView();
public FooClass(Action action) {
ConstructDesign+=action;
dataGrid.DataBindingComplete+=ConstructDesign;
}
public void Launch() {
ConstructDesign(null, new EventArgs());
}
//IN A COMPLETELY DIFFERENT CLASS:
public void Main(string[] args) {
var launcher = new FooClass(Fire);
launcher.Launch();
}
public void Fire(object sender, EventHandlerArgs args...) {
Console.WriteLine("Fired");
//and after the first fire, action will be removed from the `ConstructDesign`.
}
So basically what I’m trying to achieve here is how to do the following:
An Action that is added manually through code to ConstructDesign and upon firing, it will removes itself from the event handler, ConstructDesign. any ideas?
I haven’t found a nice way to unsubscribe from the event after the first use. (You could certainly use a reflection-heavy approach, but I doubt the compiler would complain if a refactoring changed the name of an event).
Here is one that uses only delegates, so the compiler would still serve you well. It may not be as light-weight as you need, but since I took up the challenge for my own edification, I thought I’d share it.
Where the magic is defined here:
Of course, C# won’t infer the delegate type, so you have to specify it explicitly.
If the event’s definition is EventHandler, you can use this instead:
Here’s an example program: