C#-style event accessors for CLI events in F#

牧云@^-^@ 提交于 2019-12-05 03:43:22

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

You could also wrap an event if you wanted triggering.

type MonitoredEvent<'a>(add, remove) =
    inherit Event<'a>() 

    let bp = base.Publish
    let p = { new IEvent<'a> with 
                member this.AddHandler del = 
                    add()
                    bp.AddHandler del
                member this.RemoveHandler del = 
                    remove()
                    bp.RemoveHandler del
                member this.Subscribe o = 
                    failwith "Not implemented"
                }

    member this.Publish = p

type Something() =
    let mutable listeners = 0
    let add() = listeners <- listeners + 1
    let remove() = listeners <- listeners - 1
    let me = new MonitoredEvent<_>(add, remove)

    member this.Ping x = me.Trigger (sprintf "%d %s" listeners x)

    [<CLIEvent>]
    member this.PingEvent = me.Publish

let computer = new Something()
computer.PingEvent.Add(printfn "%s")
computer.Ping "first"
computer.PingEvent.Add(printfn "-%s-")
computer.Ping "second"

output

1 first
2 second
-2 second-
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!