3

如何保护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
4

1 回答 1

10

您可以使用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 :: [] -> ...
于 2014-11-07T20:28:51.267 回答