我试图在F#中实现以下代码段:
// Method style
void Callback (NSNotification notification)
{
Console.WriteLine ("Received a notification UIKeyboard", notification);
}
void Setup ()
{
NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, Callback);
}
我做了以下事情:
let toggleKeyboard(notification : NSNotification) =
Console.WriteLine ("Received a notification UIKeyboard", notification)
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, toggleKeyboard) |> ignore
这似乎是一个简单的实现,但是我得到了一个类型错误:
This expression was expected to have type 'Action<NSNotification>' but here has type ''a -> unit' (FS0001) (Dissertation)
我不确定如何让我的方法返回Action<NSNotification>
类型。
答案 0 :(得分:3)
有时F#会自动将函数转换为Action<T>
或Func<T>
类型,但您也可以将函数显式地包装在Action<T>
中,如下所示:
let foo x = printfn "%s" x
let action = System.Action<string>(foo)
action.Invoke("hey") // prints hey
或者在你的情况下:
...AddObserver(UIKeyboard.WillShowNotification, System.Action<NSNotification>(toggleKeyboard)) |> ignore