2016-04-10 11 views
3

在瀏覽StackOverflow的我偶然發現了以下的答案:爲什麼箱子在這裏?

https://stackoverflow.com/a/3817367/162694

// ... 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 

誰能闡述爲什麼這裏的box需要?

回答

4

給出的Singleton類型沒有null作爲適當的值。換句話說,它不能爲空,通常不應該有值null。因此,將Singleton類型的值與null進行比較是不明智的,即使通過[<DefaultValue>]使用未初始化的變量可能會創建此類型的空值變量。拳擊將任何東西變成obj,這是可以爲空的,因此在這種情況下有效。

使用Unchecked.defaultof<Singleton>而不是null會使裝箱不必要和編譯。 (還有[<AllowNullLiteral>]屬性,可將其添加到Singleton類型以指定此類型的實例可能爲null。)