使用类型约束的F#模式匹配

jka*_*ane 3 f# pattern-matching type-constraints

是否可以使用成员约束执行F#类型测试模式?
如:

let f x = 
    match x with
    | :? (^T when ^T : (static member IsInfinity : ^T -> bool)) as z -> Some z
    | _ -> None  
Run Code Online (Sandbox Code Playgroud)

要么

let g x =
    match x with
    | (z :  ^T when ^T : (static member IsInfinity : ^T -> bool))  -> Some z
    | _ -> None
Run Code Online (Sandbox Code Playgroud)

没有哪个工作.

The*_*ght 5

你不能这样做,正如Petr所说,静态解析的类型参数在编译时被解析.它们实际上是F#编译器的一个功能,而不是.NET功能,因此这种信息在运行时不可用.

如果您希望在运行时检查它,可以使用反射.

let hasIsInfinity (x : 'a) =
    typeof<'a>.GetMethod("IsInfinity", [|typeof<'a>|])
    |> Option.ofObj
    |> Option.exists (fun mi -> mi.ReturnType = typeof<bool> && mi.IsStatic)
Run Code Online (Sandbox Code Playgroud)

这将检查IsInfinity使用type sig 调用的静态方法:'a -> bool