Item上的静态约束

时间:2015-12-03 14:46:49

标签: f# inline type-constraints

我试图写一个选项价值版本的" TryGetValue"这将适用于任何实现IDictionary或IReadOnlyDictionary的对象。我有这个:

let inline contains   (key:^key) (dictionary:^dic )=
    (^dic: (member ContainsKey: ^key -> bool) (dictionary, key) ) 

let inline tryGetValue (dictionary:^dic )  (key:^key)=
    if contains key dictionary then  
        let value = ( ^dic : (member  get_Item: ^key -> ^value )  (dictionary, key) )   (dictionary) ) key
        value |> Some
    else None  

"值"的定义生成一个警告,表示名称为get_Item的成员约束具有特殊状态,这可能导致运行时错误。我该怎么办?

1 个答案:

答案 0 :(得分:3)

如何使用TryGetValue代替ContainsKeyItem

let inline tryGetValue dic key =
    let mutable value = Unchecked.defaultof< ^value>
    let contains = (^dic : (member TryGetValue : ^key * byref< ^value> -> bool) (dic, key, &value))
    if contains then Some value else None