我正在学习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
如何在这种情况下初始化实例?
答案 0 :(得分:7)
我认为[<ThreadStatic>]
导致相当笨重的代码,特别是在F#中。有更简洁的方法,例如,使用ThreadLocal
:
open System.Threading
type MySingleton private () =
static let instance = new ThreadLocal<_>(fun () -> MySingleton())
static member Instance = instance.Value
答案 1 :(得分:4)
另一个F#y解决方案是将实例存储为option
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
答案 2 :(得分: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