How to match Nullable Date parameter in f#

Lin*_*ude 3 f# nullable

Learning F#, can't find the answer to this... I'd like to handle case where a Nullable parameter (DateTime? in the original c#) is null, but I get the error "Nullable does not have null as a proper value". What is the correct way to do this?

let addIfNotNull(ht:Hashtable, key:string, value:Nullable<DateTime>) = 
        match value with 
        | null -> ()
        | _ -> ht.Add(key,value)
        ht  
Run Code Online (Sandbox Code Playgroud)

Ale*_*nov 5

https://docs.microsoft.com/zh-cn/dotnet/fsharp/language-reference/symbol-and-operator-reference/nullable-operators

可以System.Nullable<'T>通过使用Value属性从对象获得实际值,并且可以System.Nullable<'T>通过调用HasValue方法确定对象是否具有值。

所以代替match

if value.HasValue then ht.Add(key, value.Value)
Run Code Online (Sandbox Code Playgroud)

你可以用

match Option.ofNullable value with ...
Run Code Online (Sandbox Code Playgroud)

或声明一些活动模式以提供帮助。

  • `Option.ofNullable`实际上在那里。 (3认同)
  • @TeaDrivenDev 谢谢!固定的。 (2认同)
  • 我必须弄清楚 Option.ofNullable 版本将与 None 而不是 null 匹配,两个版本(ofNullable,比较值属性)都可以完美工作,谢谢。 (2认同)