Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should an event be declared in an F# interface?

Tags:

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.

like image 375
kolektiv Avatar asked Nov 14 '12 14:11

kolektiv


People also ask

How do you declare an event?

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.

Can events be declared in interface?

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.

What are events in C++?

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.

How do events work in C#?

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.


1 Answers

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 
like image 151
thr Avatar answered Oct 02 '22 01:10

thr