我试图写一个选项价值版本的" 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的成员约束具有特殊状态,这可能导致运行时错误。我该怎么办?
答案 0 :(得分:3)
如何使用TryGetValue
代替ContainsKey
和Item
?
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