我想知道是否可以使用静态约束为泛型类型创建单例(下面的第三种类型不会编译)。将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
答案 0 :(得分:3)
您可以通过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
)执行此操作,但有什么意义呢?