Dot-Net

F# - 將 Concurrent.ConcurrentDictionary.TryRemove 與 dotnet 5 一起使用

  • November 20, 2020

我正在將我的 F# 程式碼從 dotnet3.1 遷移到 5,並在以下程式碼中苦苦掙扎:

       let tryRemove key (dict: Concurrent.ConcurrentDictionary<'a, 'b>) =
          match dict.TryRemove(key) with
          | (true, v) -> Some v
          | (false, _) -> None

在 3.1TryRemove返回的元組中,在版本 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 fromtryRemove

錯誤 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.1NET 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

有效,但非常奇怪的是,將最後一個參數轉換為元組結果的簡化語法不再起作用。可以?

編輯

它仍然有效!查看正確答案:)

引用自:https://stackoverflow.com/questions/64911290