与DateTime.MinValue匹配的模式?

时间:2016-11-30 12:21:19

标签: f#

我正在编写一个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

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

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

  

此字段不是文字,不能用于模式

我尝试使用的代码如下:

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

1 个答案:

答案 0 :(得分:3)

您使用的图案匹配略有错误。

以下应该有效:

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

如果要在模式匹配中测试相等性,则需要使用when子句(请参阅此处 - https://fsharpforfunandprofit.com/posts/match-expression/

相关问题