F# 项目的静态约束

F# 项目的静态约束,f#,inline,type-constraints,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:

我正在尝试编写一个选项值版本的“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  

“value”的定义会产生一个警告,即名为get_Item的成员约束具有特殊状态,这可能会导致运行时错误。我应该在这里做什么?

使用
TryGetValue
而不是
ContainsKey
怎么样

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
让内联tryGetValue dic键=
让可变值=未选中。默认值<^value>
let contains=(^dic:(成员TryGetValue:^key*byref<^value>->bool)(dic、key和value))
如果包含某个值,则其他值为无

使用
TryGetValue
而不是
ContainsKey
项如何

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
让内联tryGetValue dic键=
让可变值=未选中。默认值<^value>
let contains=(^dic:(成员TryGetValue:^key*byref<^value>->bool)(dic、key和value))
如果包含某个值,则其他值为无

我就是这样开始的,正是“Unchecked.defaultof”或者更确切地说是我不知道它的存在,让我停了下来。会不会有很多类型因为没有默认值而引发异常?@matthewjohnhath所有类型都有默认值,引用类型为null,而结构的默认值是通过将所有值类型字段设置为默认值并将所有引用类型字段设置为null而生成的值。我就是这样开始的,正是“Unchecked.defaultof”或更准确地说,我不知道这一点的存在,使我停止了。会不会有很多类型因为没有默认值而引发异常?@matthewjohnhath所有类型都有一个默认值,引用类型的默认值为null,而结构的默认值是通过将所有值类型字段设置为默认值,将所有引用类型字段设置为null而生成的值。