F#:添加和删除事件处理程序 [英] F#: Add and remove event handlers
问题描述
我正在尝试添加&从Silverlight FrameworkElement中删除事件处理程序,但我只是语法不正确.
I'm trying to add & remove an event handler from a Silverlight FrameworkElement, but I just can't get the syntax correct.
我想做这样的事情:
let clickedEventHandler = fun args -> printfn "Click!"
fe.MouseLeftButtonDown.AddHandler( clickedEventHandler)
...
fe.MouseLeftButtonDown.RemoveHandler(clickedEventHandler)
正确的方法是什么?
推荐答案
如上所述,您需要创建一个委托实例:
As you already mentioned, you need to create an instance of delegate:
let ch = new MouseButtonEventHandler(fun obj args ->
printfn "Click!")
然后,您可以将ch
用作AddHandler
或RemoveHanlder
的参数.原因是,F#函数值实际上未表示为任何委托类型.它具有自己的类型,不是委托类型(另请参阅另一篇SO讨论).如果查看F#交互式(或VS IntelliSense)中的类型,则可以看到区别:
Then you can use ch
as an argument to AddHandler
or RemoveHanlder
. The reason is, that F# function value isn't actually represented as any delegate type. It has it's own type, which isn't a delegate (see also another SO discussion). You can see the difference if you look at the types in F# interactive (or VS IntelliSense):
> (fun (o:obj) (a:MouseButtonEventArgs) -> printfn "Click!")
val it : obj -> MouseButtonEventArgs -> unit = (...)
> new MouseButtonEventHandler(fun o a -> printfn "Click!")
val it : MouseButtonEventHandler = (...)
可能令人困惑的是,F#还允许在调用方法时从lambda函数值隐式转换为兼容的委托类型,但是仅当您直接将lambda函数作为参数(我认为)时,此方法才有效:
What may be confusing is that F# also allows implicit conversion from lambda function value to a compatible delegate type when calling a method, however this works only when you give a lambda function directly as the argument (I think):
fe.MouseLeftButtonDown.AddHandler(fun obj args ->
printfn "Click!")
在F#中仍然需要委托的另一个原因是,委托具有定义明确的比较语义(将它们与任何其他引用类型进行比较).对于函数,F#规范没有说明它们何时相等.
Another reason why you still need delegates in F# is that delegates have a well-defined comparison semantics (they are compared as any other reference types). For functions, the F# specification doesn't say when they are equal.
这篇关于F#:添加和删除事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!