F# 在F中实现ThreadStatic单例#
我正在学习F#,并希望实现ThreadStatic singleton。我在用我在一个类似问题中的发现: 对于以下代码,编译器抱怨类型“MySingleton”没有“null”作为正确的值F# 在F中实现ThreadStatic单例#,f#,singleton,F#,Singleton,我正在学习F#,并希望实现ThreadStatic singleton。我在用我在一个类似问题中的发现: 对于以下代码,编译器抱怨类型“MySingleton”没有“null”作为正确的值 type MySingleton = private new () = {} [<ThreadStatic>] [<DefaultValue>] static val mutable private instance:MySingleton static me
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
type MySingleton=
私有新()={}
[]静态val可变私有实例:MySingleton
静态成员实例=
将MySingleton.instance与匹配
|null->MySingleton.instance()
MySingleton.instance
在这种情况下,我如何初始化实例?接近Ramon所说的,将
AllowNullLiteral
属性应用于类型(默认情况下,在F#中声明的类型不允许将“null”作为正确的值):
[]
类型MySingleton=
私有新()={}
[]静态val可变私有实例:MySingleton
静态成员实例=
将MySingleton.instance与匹配
|null->MySingleton.instance()
MySingleton.instance
另一个F#y解决方案是将实例存储为
type MySingleton=
私有新()={}
[; ]
静态val可变私有实例:选项
静态成员实例=
将MySingleton.instance与匹配
|无->MySingleton.instance()
MySingleton.instance.Value
我认为[]
会导致相当笨拙的代码,尤其是在F#中。有一些方法可以更简洁地做到这一点,例如,使用:
开放系统线程
键入MySingleton private()=
static let instance=new ThreadLocal(fun()->MySingleton())
静态成员实例=实例.Value
FYI您可以组合多个属性,如:[]
另一条建议--[]可以学习,但如果您关心性能,请不要在生产中使用它。还有其他实现线程键控multiton的方法,它们比[]快得多,尽管需要更多的代码。
[<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
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