【问题标题】:F# - Using Concurrent.ConcurrentDictionary.TryRemove with dotnet 5F# - 将 Concurrent.ConcurrentDictionary.TryRemove 与 dotnet 5 一起使用
【发布时间】:2020-11-19 12:03:36
【问题描述】:

我正在将我的 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

但是现在使用它的函数认为 tryRemove 的 Option 内可能有 null

错误 FS0001:类型 '(Body -> unit)' 没有 'null' 作为正确值

在哪里b' is (Body -&gt; unit)

【问题讨论】:

    标签: .net f# c#-to-f#


    【解决方案1】:

    问题在于 .NET 5 增加了一个重载。之前只有TryRemove (key : 'a, byref&lt;'b&gt; value) : bool,现在选择了新的重载TryRemove(item: KeyValuePair&lt;'a, 'b&gt;) : 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
    

    【讨论】:

      【解决方案2】:

      我刚刚想通了:

      let mutable v = Unchecked.defaultof<'b>
      

      而不是

      let mutable v: 'b = null
      

      有效,但非常奇怪的是,last out 参数 转换为 tuple result 的简化语法不再有效。是吗?

      编辑
      它仍然有效!查看正确答案:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多