Type does not have null as a proper value

前端 未结 2 672
北荒
北荒 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:42

    Use the [<AllowNullLiteral>] attribute:

    [<AllowNullLiteral>]
    type public MyClass(reasonForLiving:string) =
        member x.ReasonForLiving with get() = reasonForLiving
    

    By default, F# types do not allow null (thank heavens!). This attribute is useful for interop with other .NET languages and allows assignment/comparison with null.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题