具有静态约束

时间:2017-10-20 21:06:41

标签: generics f#

我想知道是否可以使用静态约束为泛型类型创建单例(下面的第三种类型不会编译)。将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

1 个答案:

答案 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)执行此操作,但有什么意义呢?