f# - 在 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
)
提前致谢。
解决方案
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
或者,您可以将其转换为Option
viaOption.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 -> ...
推荐阅读
- php - 如何在 PHP 中添加购物车总数
- extjs - Sencha ExtJS 如何在同一行上有两个按钮和文本
- java - 创建自定义列表视图,但值包含“@”和看起来像 C 指针的东西
- javascript - iOS移动iPhone的按钮复选框双击问题
- axapta - 无法将字段添加到表单的字段组
- excel - DOORS DXL 导出到 .xlsx 不可读...Word 中除外
- javascript - 单击时添加类,然后单击时将其删除
- python - 如何根据用户输入显示来自 CSV 的数据?
- java - 为什么在java子类中可以更容易访问字段或方法的级别访问
- pentaho - Pentaho 数据集成转换执行器