本文介绍了F#中的CLI事件的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
{
//做某事
}
删除
{
//做某事
}
}
如何在F#中写上面?
解决方案
在F#中,您可以使用 IDelegateEvent< _>
接口(或 IEvent< _>
或 IEvent 从它派生的接口)。所以你可以这样做:
let customEvent add remove =
{new IDelegateEvent< _>
成员this.AddHandler del = add del
member this.RemoveHandler del = remove del}
type MyType()=
let ev = customEvent(* your添加处理程序*)(*你的删除处理程序*)
[< CLIEvent>]
成员this.myEvent = ev
I am exposing an event from F# to C# like this:
let event = new DelegateEvent<EventHandler>()
member x.Ping() = event.Trigger([| x; EventArgs.Empty |])
[<CLIEvent>]
member x.PingEvent = event.Publish
But I'd like some code to run whenever handlers are added or removed. I think this can be done in C# like this:
public event EventHandler PingEvent
{
add
{
//do something
}
remove
{
//do something
}
}
How do I write the above in F#?
解决方案
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
这篇关于F#中的CLI事件的C#类事件访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!