Testing for null reference in F#

后端 未结 3 863
渐次进展
渐次进展 2020-12-17 15:56

Given the following:

[]
type TweetUser = {
    [] Followers:int
    [

        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 16:33

    To cyclically expand on @Tomas' answer ;-]

    let name = if not <| obj.ReferenceEquals (tweet.User, null)
                  then tweet.User.Name
                  else tweet.Sender.Name
    

    or

    let inline isNull (x:^T when ^T : not struct) = obj.ReferenceEquals (x, null)
    

    Unchecked.defaultof<_> is doing the right thing and producing nulls for your record types; the issue is that the default equality operator uses generic structural comparison, which expects you to always play by F#'s rules when using F# types. In any case, a null-check really only warrants referential comparison in the first place.

提交回复
热议问题