如何使用DateTime.TryParseExact
进行防护(并在可能的情况下获取解析值)?以下代码不起作用。
[<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) -> ...
但一个活跃的模式使匹配更加清晰:
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 :: [] -> ...