I am exposing an event from F# to C# like this:
let event = new DelegateEvent<EventHandler>()
member x.Ping() = event.Trigger([| x; EventArgs.Empty |])
[<CLIEvent>]
member x.PingEvent = event.Publish
But I'd like some code to run whenever handlers are added or removed. I think this can be done in C# like this:
public event EventHandler PingEvent
{
add
{
//do something
}
remove
{
//do something
}
}
How do I write the above in F#?
In F#, you can define events with implementations of the IDelegateEvent<_>
interface (or the IEvent<_>
or IEvent<_,_>
interfaces which derive from it). So you can do something like this:
let customEvent add remove =
{ new IDelegateEvent<_> with
member this.AddHandler del = add del
member this.RemoveHandler del = remove del }
type MyType() =
let ev = customEvent (* your add handler *) (* your remove handler *)
[<CLIEvent>]
member this.myEvent = ev
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With