F# 泛型类型约束可以指定超过 1 个有效类型吗?

Mat*_*and 4 generics f#

我有这个示例函数签名:

let func1 (input:'a when 'a :> (IReadOnlyDictionary<string, string>)) =
...
Run Code Online (Sandbox Code Playgroud)

我也想允许'a成为一名IDictionary<string, string>). 所以任何一种类型都可以通过。input使用两个接口都支持的参数调用的代码TryGetValue

是否可以指定这样的 OR 类型约束?如果是这样,那么具体的语法是什么?

bri*_*rns 5

我很确定你不能,但你可以使用SRTP来请求该TryGetValue方法:

let inline func1 (input : 'a when 'a : (member TryGetValue : string * byref<string> -> bool)) =
    let mutable value = ""
    let flag = input.TryGetValue("key", &value)
    flag, value
Run Code Online (Sandbox Code Playgroud)

它很丑,但很有效。这里用一个来调用它IDictionary

dict [ "key", "value" ]
    |> func1
    |> printfn "%A"   // (true, "value")
Run Code Online (Sandbox Code Playgroud)

在这里它被称为IReadOnlyDictionary

dict [ "key", "value" ]
    |> System.Collections.ObjectModel.ReadOnlyDictionary
    :> System.Collections.Generic.IReadOnlyDictionary<_, _>
    |> func1
    |> printfn "%A"   // (true, "value")
Run Code Online (Sandbox Code Playgroud)