Dot-Net
F# - 將 Concurrent.ConcurrentDictionary.TryRemove 與 dotnet 5 一起使用
我正在將我的 F# 程式碼從 dotnet3.1 遷移到 5,並在以下程式碼中苦苦掙扎:
let tryRemove key (dict: Concurrent.ConcurrentDictionary<'a, 'b>) = match dict.TryRemove(key) with | (true, v) -> Some v | (false, _) -> None在 3.1
TryRemove返回的元組中,在版本 5 中它只返回布爾值。要從字典中獲取值,我需要將引用作為TryRemove. 什麼是正確的方法來避免返回 null v?我試過以下程式碼:
let tryRemove key (dict: Concurrent.ConcurrentDictionary<'a, 'b>): 'b option = let mutable v: 'b = null match dict.TryRemove(key, &v) with | true -> Some v | _ -> None但是現在使用它的函式認為它可以在該選項中包含 null from
tryRemove錯誤 FS0001:類型 ‘(Body -> unit)’ 沒有 ’null’ 作為正確值
在哪裡
b' is (Body -> unit)
問題是 .NET 5 增加了一個重載。以前只有
TryRemove (key : 'a, byref<'b> value) : bool,現在選擇了新的重載TryRemove(item: KeyValuePair<'a, 'b>) : bool。參見netcore 3.1與NET 5另一種解決方案是添加類型註釋,例如
let tryRemove (key: 'a) (dict: Concurrent.ConcurrentDictionary<'a, 'b>) = match dict.TryRemove(key) with | (true, v) -> Some v | (false, _) -> None
我剛剛想通了:
let mutable v = Unchecked.defaultof<'b>代替
let mutable v: 'b = null有效,但非常奇怪的是,將最後一個參數轉換為元組結果的簡化語法不再起作用。可以?
編輯
它仍然有效!查看正確答案:)