4

我正在学习 F# 并想实现 ThreadStatic 单例。我正在使用在类似问题中找到的内容:F# How to implement Singleton Pattern (syntax)

使用以下代码编译器抱怨The type 'MySingleton' does not have 'null' as a proper value.

type MySingleton = 
    private new () = {}
    [<ThreadStatic>] [<DefaultValue>] static val mutable private instance:MySingleton
    static member Instance =
        match MySingleton.instance with
        | null -> MySingleton.instance <- new MySingleton()
        | _ -> ()
        MySingleton.instance

在这种情况下如何初始化实例?

4

3 回答 3

8

我认为[<ThreadStatic>]会导致代码相当笨拙,尤其是在 F# 中。有一些方法可以更简洁地做到这一点,例如,使用ThreadLocal

open System.Threading

type MySingleton private () = 
  static let instance = new ThreadLocal<_>(fun () -> MySingleton())
  static member Instance = instance.Value
于 2012-11-09T15:20:03.000 回答
4

另一个 F#y 解决方案是将实例存储为选项

type MySingleton = 
    private new () = {}

    [<ThreadStatic>; <DefaultValue>]
    static val mutable private instance:Option<MySingleton>

    static member Instance =
        match MySingleton.instance with
        | None -> MySingleton.instance <- Some(new MySingleton())
        | _ -> ()

        MySingleton.instance.Value
于 2012-11-09T13:36:55.163 回答
3

接近 Ramon 所说的,将AllowNullLiteral属性应用于类型(默认情况下,在 F# 中声明的类型不允许 'null' 作为适当的值):

[<AllowNullLiteral>]
type MySingleton = 
    private new () = {}
    [<ThreadStatic>] [<DefaultValue>] static val mutable private instance:MySingleton
    static member Instance =
        match MySingleton.instance with
        | null -> MySingleton.instance <- new MySingleton()
        | _ -> ()
        MySingleton.instance
于 2012-11-09T12:54:46.620 回答