我正在从F#向C#发布一个事件:
let event = new DelegateEvent<EventHandler>() member x.Ping() = event.Trigger([| x; EventArgs.Empty |]) [<CLIEvent>] member x.PingEvent = event.Publish
但是,我希望在处理程序被添加或删除时运行一些代码.我认为这可以在C#中这样做:
public event EventHandler PingEvent { add { //do something } remove { //do something } }
如何在F#中写上面的内容?
解决方法@H_301_12@
在F#中,您可以使用IDelegateEvent< _>接口(或从其导出的IEvent …或IEvent,_,_>接口).所以你可以这样做:
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
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