简体   繁体   English

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

[英]F# pattern match using type constraints

Is it possible to do an F# type test pattern with a member constraint? 是否可以使用成员约束执行F#类型测试模式?
Such as: 如:

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

or 要么

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

Neither which work. 没有哪个工作。

You cannot do this, as Petr said, statically resolved type parameters are resolved at compile time. 你不能这样做,正如Petr所说,静态解析的类型参数在编译时被解析。 They're actually a feature of the F# compiler rather than being a .NET feature, hence why this kind of information isn't available at runtime. 它们实际上是F#编译器的一个功能,而不是.NET功能,因此这种信息在运行时不可用。

If you wish to check this at runtime, you could use reflection. 如果您希望在运行时检查它,可以使用反射。

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

This will check for a static method called IsInfinity with type sig: 'a -> bool 这将检查名为IsInfinity的静态方法,类型为sig: 'a -> bool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM