【问题标题】:Pattern Matching with DateTime.MinValue?与 DateTime.MinValue 的模式匹配?
【发布时间】:2016-11-30 12:21:19
【问题描述】:

我正在编写一个 F# 服务,它使用 Quartz.Net 来轮询另一个服务(已用 C# 编写):

[<PersistJobDataAfterExecution>]
[<DisallowConcurrentExecution>]
type PollingJob() = 
    interface IJob with 
        member x.Execute(context: IJobExecutionContext) = 
           let uri = "http://localhost:8089/"
           let storedDate = context.JobDetail.JobDataMap.GetDateTime("LastPoll") 
           //this works...
           let effectiveFrom = (if storedDate = DateTime.MinValue then System.Nullable() else System.Nullable(storedDate))

           let result = someFunction uri effectiveFrom

           context.JobDetail.JobDataMap.Put("LastPoll", DateTime.UtcNow) |> ignore

context 由 Quartz 为每个轮询传递给 Execute 函数,并包含一个字典。服务第一次运行LastPoll 的值将是默认的DateTime 值,即01/01/0001 00:00:00。然后调度程序下一次运行LastPoll 将包含上次轮询的时间。

我可以使用if..then..else 构造(上图)创建Nullable&lt;DateTime&gt;,但是当我尝试使用模式匹配时,我在DateTime.MinValue 下得到一个带有波浪形的编译器错误:

此字段不是文字,不能在模式中使用

我尝试使用的代码如下:

//this doesn't...
let effectiveFrom = 
    match storedDate with 
    | DateTime.MinValue -> System.Nullable()
    | _ -> System.Nullable(storedDate)

【问题讨论】:

    标签: f#


    【解决方案1】:

    您使用的模式匹配略有错误。

    以下应该可以工作:

        let effectiveFrom = 
            match storedDate with 
            | d when d = DateTime.MinValue -> System.Nullable()
            | _                            -> System.Nullable(storedDate)
    

    当您想在模式匹配中测试相等性时,您需要使用 when 子句(参见此处 - https://fsharpforfunandprofit.com/posts/match-expression/

    【讨论】:

    • 效果很好,谢谢。并感谢您提供链接。
    猜你喜欢
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多