The standard way to publish events in F# now seems to be the following:
type MyDelegate = delegate of obj * EventArgs -> unit type MyType () = let myEvent = new Event<MyDelegate, EventArgs> () [<CLIEvent>] member this.OnMyEvent = myEvent.Publish
and that works fine, including being able to consume that event from other .NET languages (C# at least that I've tested). But how can you make that event show up in an interface? Here's what I'm trying...
type MyDelegate = delegate of obj * EventArgs -> unit type IMyType = abstract member OnMyEvent : IEvent<MyDelegate, EventArgs> type MyType () = let myEvent = new Event<MyDelegate, EventArgs> () interface IMyType with [<CLIEvent>] member this.OnMyEvent = myEvent.Publish
But that won't compile - the member within the interface causes an error: "No abstract or interface member was found that corresponds to this override". How should I be declaring the event in my interface? Or is it that my member syntax is wrong?
Note - this is not about consuming C# events in F# or general event usage in F# - the interface aspect is key.
Use "event" keyword with delegate type variable to declare an event. Use built-in delegate EventHandler or EventHandler<TEventArgs> for common events. The publisher class raises an event, and the subscriber class registers for an event and provides the event-handler method.
An interface can declare an event. The following example shows how to implement interface events in a class. Basically the rules are the same as when you implement any interface method or property.
In native C++ event handling, you set up an event source and event receiver using the event_source and event_receiver attributes, respectively, specifying type = native . These attributes allow the classes they're applied on to fire events and handle events in a native, non-COM context.
Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.
You need to specify the CLIEvent attribute on both the interface and the implementation.
open System; type MyDelegate = delegate of obj * EventArgs -> unit type IMyType = [<CLIEvent>] abstract member OnMyEvent : IEvent<MyDelegate, EventArgs> type MyType () = let myEvent = new Event<MyDelegate, EventArgs> () interface IMyType with [<CLIEvent>] member this.OnMyEvent = myEvent.Publish
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