是否可以使用成员约束执行 F# 类型测试模式?
如:
let f x =
match x with
| :? (^T when ^T : (static member IsInfinity : ^T -> bool)) as z -> Some z
| _ -> None
或者
let g x =
match x with
| (z : ^T when ^T : (static member IsInfinity : ^T -> bool)) -> Some z
| _ -> None
无论哪个工作。
最佳答案
您不能这样做,正如 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)
这将检查名为
IsInfinity
的静态方法。类型为:'a -> bool
关于使用类型约束的 F# 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36750513/