开发者

Implementing C# EventHandlers in F#

开发者 https://www.devze.com 2023-01-07 13:55 出处:网络
I have an interface, written in C#, defined as this : public interface IWidget { object Evaluate(); event EventHandler Invalidated;

I have an interface, written in C#, defined as this :

public interface IWidget
{
    object Evaluate();
    event EventHandler Invalidated;
}

When I try to implement this interface in F#, I look at what F# thinks the IWidget interface is (by hovering my mouse over it), and I see

type IWidget = 
    interface
        member Evaluate : unit -> obj
    end

It appears to ignore the Invalidated event entirely... is this a known issue with F# and if so is there any way to work arou开发者_Go百科nd it? When implementing my F# version of IWidget, can I just implement this event outside of the IWidget section or what? It seems really nasty that f# handles the "event" keyword so poorly...

UPDATE: After further fiddling around, studio was then saying things like:

'no implementation was given for IWidget.remove_Invalidate(value:EventHandler):unit'

then, when I added those methods so the whole thing looked like:

interface IWidget with
    member w.Evaluate() = new obj()
    member w.add_Invalidated(value:EventHandler) = ()
    member w.remove_Invalidated(value:EventHandler) = ()
end

it compiled fine, even though the tooltip was still saying the only member of IWidget was Evaluate()... it seems like the way F# (or at least the IDE) handles this stuff is really screwy...

ANOTHER UPDATE: According to the tooltip in the IDE, the [] tag allows an event to be compiled as a CLI metadata event, by transforming it to a pair of add_/remove_ methods... just FYI for anyone who was as confused by this as I was. In short, either implementing those two methods or using that tag work fine, though the fact that the tooltip view of the IWdiget interface lacks any mention of the Invalidate event, and the necessity of implementing such an event is only noticed when the compiler throws an error, is still a clear bug and is pretty confusing. For anyone curious, the following code works fine:

let invalidated = new DelegateEvent<System.EventHandler>()

interface IWidget with
    member w.Evaluate() = new obj()
    [<CLIEvent>]
    member w.Invalidated = invalidated.Publish
end

Thanks for all the help everyone!


F# does support events.

For example:

let invalidated = new DelegateEvent<System.EventHandler>()

[<CLIEvent>]
member this.Invalidated = invalidated.Publish
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号