我有这个示例函数签名:
let func1 (input:'a when 'a :> (IReadOnlyDictionary<string, string>)) =
...
我也想允许'a
成为IDictionary<string, string>)
。所以两种类型都可以传递。使用input
参数的代码调用两个接口都支持的TryGetValue
。
有可能像这样指定OR类型约束吗?如果是,具体的语法是什么?
我很确定你不能,但你可以使用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
它是丑陋的,但它工作。这里用IDictionary
来调用:
dict [ "key", "value" ]
|> func1
|> printfn "%A" // (true, "value")
这里是IReadOnlyDictionary
:
dict [ "key", "value" ]
|> System.Collections.ObjectModel.ReadOnlyDictionary
:> System.Collections.Generic.IReadOnlyDictionary<_, _>
|> func1
|> printfn "%A" // (true, "value")