f# - SingleOrDefault() 在 F# 中抛出 NullReferenceException

标签 f#

<分区>

下面的代码在 FirstOrDefault() 方法中抛出一个 NullReferenceException:

open System
open System.Collections.Generic
open System.Linq

[<EntryPoint>]
let main argv = 
    let suspects = seq {
        yield ("Frank", 1.0)
        yield ("Suzie", 0.9)
        yield ("John", 0.5)
        // yield ("Keyser Soze", 0.3)
    }
    let likely = suspects.FirstOrDefault(fun (name, confidence) -> name = "Keyser Soze")
    printfn "Name: %s" (fst likely)
    Console.ReadLine() |> ignore
    0

解决该问题的最佳方法是什么?捕获它似乎是错误的。我可以手动获取迭代器并将其放入一个 while 循环中,但这在很多层面上都是错误的。

[编辑] 我什至不能做我在 C# 中会做的事情,即检查结果是否为 null 或 default,原因有二:(1) 在 FirstOrDefault() 方法中抛出错误,而不是当我引用结果时; (2) 如果我尝试检查 null,编译器会提示“类型‘(string * float)’没有‘null’作为正确的值”:

    if likely = null then            
        printfn "Nothing to see here"

有什么建议吗?

最佳答案

如上所述,Seq.tryFind 是实现该目标的惯用方法。如果你真的必须使用 FirstOrDefault() 你可以这样做:

open System.Collections.Generic
open System.Linq
let suspects = seq {
    yield Some("Frank", 1.0)
    yield Some("Suzie", 0.9)
    yield Some("John", 0.5)
    // yield ("Keyser Soze", 0.3)
}
let likely = suspects.FirstOrDefault(fun x -> let name, confidence = x.Value
                                              name = "Keyser Soze")
match likely with
| Some(x) -> printfn "Name: %s" (fst x)
| None -> printfn "Not Found"

关于f# - SingleOrDefault() 在 F# 中抛出 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17620061/

相关文章:

f# - 为什么不允许 F# 记录具有 AllowNullLiteralAttribute?

f# - 使用 F# 和 Open XML SDK 读取 Excel 文件中的单元格内容

f# - 为什么不允许我在 let 函数中使用引用单元格作为 byref 参数的参数?

performance - F#中的慢尾递归

haskell - 类型类的替代品?

exception - F#异常处理构造

f# - 类型提供者中奇怪的 None 行为

mongodb - F# MongoDB 使用带有字符串过滤器的查找

f# - 引用外部程序集失败

.net - 当 Generic.List<T>.Add 是函数中的最后一个语句并且尾调用优化开启时的性能损失