使用DateTime.TryParseExact进行模式匹配防护? [英] Pattern match guard with DateTime.TryParseExact?

查看:57
本文介绍了使用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进行模式匹配防护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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