Type does not have null as a proper value

前端 未结 2 660
北荒
北荒 2021-01-03 19:08

For the sample program:

type public MyClass(reasonForLiving:string) =
    member x.ReasonForLiving with get() = reasonForLiving

let classFactory () = MyClas         


        
2条回答
  •  迷失自我
    2021-01-03 19:44

    The problem with the AllowNullLiteral attribute is that in addition to allowing you to compare your objects to null, it also makes it possible to set your objects to null.

    Assuming that this is not desirable for your use-case, there is an easy alternative with unobservable performance impact:

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

    Then rather than doing if instance = null then, do if isNull instance then instead.

    This will work for any reference type (including records and DUs), but does not introduce the possibility of setting objects of your F# types to null from F# – the best of both worlds.

提交回复
热议问题