简体   繁体   English

函数返回值中的F#类型错误

[英]F# type error in function return value

I'm trying to implement the following code snippet in F#: 我正在尝试在F#中实现以下代码段:

    // Method style
void Callback (NSNotification notification)
{
    Console.WriteLine ("Received a notification UIKeyboard", notification);
}

void Setup ()
{
    NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, Callback);
}

I have done the following: 我做了以下事情:

let toggleKeyboard(notification : NSNotification) = 
    Console.WriteLine ("Received a notification UIKeyboard", notification)

NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, toggleKeyboard) |> ignore

This seems like a straightforward implementation, however I get a type error: 这似乎是一个简单的实现,但我得到一个类型错误:

This expression was expected to have type 'Action<NSNotification>' but here has type ''a -> unit' (FS0001) (Dissertation)

I'm not really sure how to make my method return a Action<NSNotification> type. 我不确定如何让我的方法返回一个Action<NSNotification>类型。

Sometimes F# will automatically cast functions to Action<T> or Func<T> types, but you can also explicitly wrap your function in an Action<T> like this: 有时F#会自动将函数Func<T>Action<T>Func<T>类型,但您也可以将函数显式地包装在Action<T>如下所示:

let foo x = printfn "%s" x
let action = System.Action<string>(foo)
action.Invoke("hey") // prints hey

Or in your case: 或者在你的情况下:

...AddObserver(UIKeyboard.WillShowNotification, System.Action<NSNotification>(toggleKeyboard)) |> ignore

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM