加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – F#:实现“try cast”功能,参数化“子类型”约束不起作用

发布时间:2020-12-15 22:51:46 所属栏目:百科 来源:网络整理
导读:参见英文答案 How to constrain one type parameter by another????????????????????????????????????1个 我正在尝试在F#中实现“try cast”运算符.约束的子类型不起作用. 举个例子,我想用C#做什么: static A TryCastTSuper,TSub,A( FuncTSub,A f,FuncTSupe
参见英文答案 > How to constrain one type parameter by another????????????????????????????????????1个
我正在尝试在F#中实现“try cast”运算符.约束的子类型不起作用.

举个例子,我想用C#做什么:

static A TryCast<TSuper,TSub,A>(
    Func<TSub,A> f,Func<TSuper,A> g,TSuper x)
    where TSub : TSuper
    =>
    x is TSub sub ? f(sub) : g(x);

F#中的等价物应该是:

let tryCast<'super,'sub when 'sub :> 'super>
    (f : 'sub -> 'a) (g: 'super -> 'a) (x : 'super) : 'a =
        match x with
        | :? 'sub as sub -> f sub
        | x              -> g x

要么

... 
if x :? 'sub then f (x :?> 'sub) else g x

但是,它给了我一个错误“’sub”在“when”子句中被限制为总是’super’.
这似乎表明F#不支持这一点.但我觉得奇怪的是我可以在C#中做到这一点.

所以问题是:这可以在F#中完成吗?

解决方法

感谢链接解释它确实是一个F#限制:
How to constrain one type parameter by another

我想分享我找到的针对特定案例的(次优)解决方法:

let tryCastWith
    (success : 'sub -> 'a) (fallback: 'super -> 'a) (x : 'super) : 'a =
    let o = box x
    if o :? 'sub then success (o :?> 'sub) else fallback x

更具体地说,我实际想要的功能是这样的:

let tryCast (x : 'super) : Choice<'sub,'super> =
    tryCastWith Choice1Of2 Choice2Of2 x

这使铸件和消耗分离.为了使用第二个函数,有必要让F#推断’sub’或者给出一个显式类型注释.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读