我正在学习F#并希望实现ThreadStatic单例.我正在使用我在类似问题中找到的内容:F#如何实现Singleton Pattern(语法)
使用以下代码编译器抱怨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
Run Code Online (Sandbox Code Playgroud)
我如何在这种情况下初始化实例?
我认为[<ThreadStatic>]导致相当笨重的代码,特别是在F#中.有更简洁的方法可以做到这一点,例如,使用ThreadLocal:
open System.Threading
type MySingleton private () =
static let instance = new ThreadLocal<_>(fun () -> MySingleton())
static member Instance = instance.Value
Run Code Online (Sandbox Code Playgroud)