F#中泛型类型的运行时强制 [英] Runtime coercion of generic types in F#

查看:69
本文介绍了F#中泛型类型的运行时强制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在F#中有一个带有显式泛型参数的基类.我正在尝试检查我正在使用的给定类型是否实现了特定的接口.我以为"if ob:?ISysAware then"可以,但是抱怨总是一样的:

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

错误FS0008:从类型'a到ISysAware的此运行时强制或类型测试涉及一个不确定的类型,该类型基于此程序点之前的信息.在某些类型上不允许运行时类型测试.需要进一步的类型注释.

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.

显然,我不想在这里使用反射. IsAssignableFrom可以解决这个问题,而且成本很高.

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

有想法吗?

推荐答案

某些F#类型是值类型;添加box可确保仅对引用类型执行类型测试:

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

这篇关于F#中泛型类型的运行时强制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆