[英]F# singleton for generic type with static constraint
我想知道是否可以為具有靜態約束的泛型類型創建單例(以下第三個類型將無法編譯)。 inline
添加到第三種類型的成員不起作用。 非常感謝!
type A private () =
static let instance = A ()
static member Instance = instance
member this.DoNothing (x : int) = 0
type GenericA<'B> private () =
static let instance = GenericA<'B> ()
static member Instance = instance
member this.DoNothing (x : 'B) = 0
type GenericWithStaticConstraintA<'B when 'B : (static member MyMember : Unit -> int)> private () =
static let instance = GenericWithStaticConstraintA<'B> ()
static member Instance = instance
member this.DoNothing (x : 'B) = 0
您可以通過inline
關鍵字在靜態成員的類上使用靜態解析的類型約束。
type GenericWithStaticConstraintA< ^B when ^B : (static member MyMember : unit -> int)> =
static member inline DoNothing(x : ^B) = 0
例:
type Foo = Foo with static member MyMember() = 42
type Bar = Bar with static member MyMember = fun () -> 42
GenericWithStaticConstraintA.DoNothing(Foo)
GenericWithStaticConstraintA.DoNothing(Bar) // The type 'Bar' does not support the operator 'MyMember'
您也可以使用實例成員( member inline __.DoNothing(x : ^B) = 0
)來執行此操作,但是這樣做的目的是什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.