为什么盒子在这里?

Sna*_*ake 3 f# boxing

在浏览StackOverflow时,我偶然发现了以下答案:

/sf/answers/267215721/

// ... removed unneeded code
/// This type is intended for private use within Singleton only.
type private SyncRoot = class end

type Singleton =
    [<DefaultValue>]
    static val mutable private instance: Singleton

    private new() = { }

    static member Instance = 
        lock typeof<SyncRoot> (fun() ->
            // vvv
            if box Singleton.instance = null then
            // ^^^
                Singleton.instance <- Singleton())
        Singleton.instance  
Run Code Online (Sandbox Code Playgroud)

有人可以详细说明为什么box需要这里吗?

Van*_*oiy 5

给定Singleton类型没有null适当的值.换句话说,它不可空,通常不应该有价值null.因此,将类型值Singleton与其进行比较是不明智的null,即使使用未初始化的变量via [<DefaultValue>]可能会创建此类型的空值变量.拳击将任何东西都变成了obj可以为空的,因此在这种情况下是有效的.

使用Unchecked.defaultof<Singleton>而不是null使拳击不必要和编译.(还有一个[<AllowNullLiteral>]属性,可以添加到Singleton类型中以指定此类型的实例可以null.)