如何在 f# 中匹配 Nullable Date 参数
How to match Nullable Date parameter in f#
正在学习 F#,找不到答案...我想处理 Nullable 参数(原始 c# 中的 DateTime?)为 null 的情况,但出现错误 "Nullable does not have null as a proper value".正确的做法是什么?
let addIfNotNull(ht:Hashtable, key:string, value:Nullable<DateTime>) =
match value with
| null -> ()
| _ -> ht.Add(key,value)
ht
The actual value can be obtained from a System.Nullable<'T>
object by using the Value
property, and you can determine if a System.Nullable<'T>
object has a value by calling the HasValue
method.
所以你
而不是 match
if value.HasValue then ht.Add(key, value.Value)
你可以使用
match Option.ofNullable value with ...
或声明一些活动模式来提供帮助。
虽然@AlexeyRomanov 的回答是完全有效的,但如果你真的想匹配一个 Nullable
值,你可以像这样定义一个活动模式:
let (|Null|Value|) (x : _ Nullable) =
if x.HasValue then Value x.Value else Null
然后在你的函数中使用它:
let addIfNotNull (ht : Hashtable) (key : string)
(value : Nullable<DateTime>) =
match value with
| Null -> ()
| Value dt -> ht.Add (key, dt)
ht
我冒昧地更改了您的函数的签名,因此它采用柯里化参数;除非您有特定要求,否则柯里化参数通常优于元组参数。
正在学习 F#,找不到答案...我想处理 Nullable 参数(原始 c# 中的 DateTime?)为 null 的情况,但出现错误 "Nullable does not have null as a proper value".正确的做法是什么?
let addIfNotNull(ht:Hashtable, key:string, value:Nullable<DateTime>) =
match value with
| null -> ()
| _ -> ht.Add(key,value)
ht
The actual value can be obtained from a
System.Nullable<'T>
object by using theValue
property, and you can determine if aSystem.Nullable<'T>
object has a value by calling theHasValue
method.
所以你
而不是match
if value.HasValue then ht.Add(key, value.Value)
你可以使用
match Option.ofNullable value with ...
或声明一些活动模式来提供帮助。
虽然@AlexeyRomanov 的回答是完全有效的,但如果你真的想匹配一个 Nullable
值,你可以像这样定义一个活动模式:
let (|Null|Value|) (x : _ Nullable) =
if x.HasValue then Value x.Value else Null
然后在你的函数中使用它:
let addIfNotNull (ht : Hashtable) (key : string)
(value : Nullable<DateTime>) =
match value with
| Null -> ()
| Value dt -> ht.Add (key, dt)
ht
我冒昧地更改了您的函数的签名,因此它采用柯里化参数;除非您有特定要求,否则柯里化参数通常优于元组参数。