如何在通用约束类型

时间:2018-06-18 10:20:10

标签: f#

给出了这个例子:

type Base() =
    static member Function() = ""

type Derived() =
    inherit Base()

let get<'T when 'T :> Base> segment =
    return ('T).Function()

let invoked = get<Derived>()

有没有办法从Function拨打get

1 个答案:

答案 0 :(得分:6)

SRTP可以帮助您:

type Base() =
    static member Function() = ""

type Derived() =
    inherit Base()

let inline get< ^T 
        when ^T :> Base
        and  ^T : (static member Function: unit -> string)> =
     (^T : (static member Function: unit -> string) ())

let invoked1 = get<Derived>  //ok
let invoked2 = get<string>   //error: string not derived from Base