简体   繁体   中英

Runtime coercion of generic types in F#

I have a base class with explicit generic arguments in F#. I'm trying to check if the given type I'm using implements a specific interface. I thought "if ob :? ISysAware then" would do, but the complain is always the same:

let (|SysAware|_|) t = 
    match t with
    | :? ISysAware as p -> Some(p)
    | _ -> None

error FS0008: This runtime coercion or type test from type 'a to ISysAware involves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed.

I'd prefer not to use reflection here, obviously. IsAssignableFrom would do the trick, at a high cost.

Thoughts?

Some F# types are value types; adding box ensures that type test is performed on reference types only:

let (|SysAware|_|) t = 
    match box t with
    | :? ISysAware as p -> Some(p)
    | _ -> None

The reason for the error is the type checker being confused as it can't work out the type, the solution - similar to pad's is to add a type annotation

let (|SysAware|_|) (t:obj) = 
    match t with
    | :? ISysAware as p -> Some(p)
    | _ -> None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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