我正在学习F#,并且想实现ThreadStatic singleton。我使用的是我在一个类似的问题中发现的: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在此场景下,如何初始化实例?
发布于 2012-11-09 23:20:03
我认为[<ThreadStatic>]会导致相当笨重的代码,尤其是在F#中。有一些方法可以更简洁地实现这一点,例如,使用ThreadLocal
open System.Threading
type MySingleton private () =
static let instance = new ThreadLocal<_>(fun () -> MySingleton())
static member Instance = instance.Value发布于 2012-11-09 21:36:55
另一种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发布于 2012-11-09 20:54:47
接近拉蒙所说的,将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.instancehttps://stackoverflow.com/questions/13308090
复制相似问题