F# - 警告我没有明确声明类型参数

时间:2017-07-28 00:43:18

标签: generics types f#

假设:

type Service = Object
type Services = ConcurrentDictionary<Type, Service>

为什么这样:

// If we use this form, we get a compiler warning:
type GetService<'T> = Services -> 'T
let GetService:GetService<'T> = fun services ->
    services.[typeof<'T>] :?> 'T

产生警告:

“方法或函数'GetService'不应该被赋予显式类型参数,因为它没有声明其类型参数明显。”

但这不是:

let GetService<'T> (services : Services) =
    services.[typeof<'T>] :?> 'T

使用示例:

let someService = services |> GetService<SomeServiceType>

如果我想更正第一个版本以免收到警告,我该如何更改定义?

1 个答案:

答案 0 :(得分:2)

只需给它一个类型参数,如错误消息所示。这应该有效:

let GetService<'T> : GetService<'T> = fun services ->
    services.[typeof<'T>] :?> 'T