在null/empty值上使用bool.Parse时出错 [英] Error using bool.Parse on null/empty values

查看:70
本文介绍了在null/empty值上使用bool.Parse时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用管道运算符的表达式,该表达式将值转换为字符串,然后转换为bool,但是有时原始值可以为null. 当值为null时,如何使用模式匹配或其他方式假设为false?

I have an expression using pipe operator that converts the value to string and then to bool, however sometimes the original value can be null. How can I use the pattern matching or something else to assume false when the value is null?

type kv = Dictionary<string, obj>
let allDayEvent (d: kv) = d.["fAllDayEvent"] |> string |> bool.Parse

推荐答案

在很多地方都可以通过模式匹配来保护:字典查找,转换,解析.这是所有这些的示例:

There's quite a few places where you can safeguard via pattern matching: dictionary lookup, casting, parsing. Here's an example with all of those:

let allDayEvent (d: kv) = 
    match d.TryGetValue "fAllDayEvent" with
    | true, v ->
        match v with
        | null -> printfn "null found"
        | :? string as s -> 
            match bool.TryParse s with
            | true, b -> printfn "found a bool: %A" b
            | _ -> printfn "That's not a bool?"
        | v -> printfn "Found something of type %s" (v.GetType().Name)
    | _ -> printfn "No such key"

另请参见相关问题,例如 .

See also related questions, for example this.

这篇关于在null/empty值上使用bool.Parse时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆