本文介绍了使用DateTime.TryParseExact进行模式匹配防护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用DateTime.TryParseExact保护(并在可能的情况下获取解析的值)?以下代码不起作用.
How to guard with DateTime.TryParseExact (and get the parsed value if possible)? The following code doesn't work.
[<EntryPoint>] let main args = let argList = args |> List.ofSeq match argList with | "aaa" :: [] -> aaa.main "aaa" | "bbb" :: [] -> bbb.main "bbb" | "ccc" :: yyyymm :: [] when DateTime.TryParseExact (yyyymm, "yyyyMM", CultureInfo.InvariantCulture, DateTimeStyles.None)-> ccc.main "ccc" yyyymm推荐答案
您可以使用mutable:
let mutable dt = Unchecked.defaultof<_> match argList with | "ccc" :: yyyymm :: [] when DateTime.TryParseExact(yyyymm, "yyyyMM", CultureInfo.InvariantCulture, DateTimeStyles.None, &dt) -> ...但是有效的模式使匹配更加清晰:
But an active pattern makes the match much clearer:
let (|DateTimeExact|_|) (format: string) s = match DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.None) with | true, d -> Some d | _ -> None match argList with | "ccc" :: DateTimeExact "yyyyMM" yyyymm :: [] -> ...更多推荐
使用DateTime.TryParseExact进行模式匹配防护?
发布评论