首页 > 解决方案 > 在 F# 中,如何对 Nullable 进行模式匹配反对空?

问题描述

(真的很困惑)。

请假设我从 WCF 服务下载了访问:

type Visit = {
               tservice : Nullable<DateTime>
             }

和一个由访问组成的访问数组。假设数组中的一些访问具有非空 tservice 而其他访问具有空 tservice 值,那么 tservice 模式如何与空匹配?

即这失败了:,

let fillSchedule (v:Visits[]) =
       v |> Array.iter ( fun f -> 
                            match f.tservice with
                            | System.Nullable<DateTime>  -> tservice IS null, do something
                            | _ -> tservice is NOT null,  do something
            
                       )

提前致谢。

标签: f#nullable

解决方案


Nullable不是 F# 类型,它来自更广泛的 .NET,因此不能对它进行模式匹配。您可以检查其.HasValue属性以查看它是否具有值:

if f.tservice.HasValue
    then tservice is NOT null, do something with f.tservice.Value
    else tservice IS null, do something

或者,您可以将其转换为OptionviaOption.ofNullable并对结果进行模式匹配:

match Option.ofNullable f.tservice with
| Some v -> ...
| None -> ...

如果您必须与推Nullable送到您身上的 .NET 代码进行互操作,恐怕这是您能做的最好的事情。但是,如果您自己控制代码库,我建议您使用Option而不是Nullable开始。它可以进行模式匹配,并且在模块中有一些漂亮的功能可以使用它Option


最后,如果你真的需要使用Nullable,但也真的很想对其进行模式匹配,你可以制作自己的匹配器:

let (|Null|NotNull|) (n: Nullable<_>) =
    if n.HasValue then NotNull n.Value else Null

// Usage:    
match f.tservice with
| Null -> ...
| NotNull v -> ...

推荐阅读