重写一些C#泛型代码为F# [英] Rewrite some C# generic code into F#

查看:169
本文介绍了重写一些C#泛型代码为F#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图改写像这样(C#)的通用代码:

I'm trying to rewrite generic code like this (C#):

U Upcast<T, U>(T x) where T : U { return x; }

在F#:

let ucast<'T, 'U when 'T :> 'U> (x: 'T) = x :> 'U



但F#约束求解的作品比C#不同的编译器输出一堆键入错误的:

But F# constraint solving works different than C# and compiler outputs a bunch of typing errors:

错误FS0698:无效的约束:用来约束的
型为
密封,这意味着约束
只能通过最多一个
解决方案

error FS0698: Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution

警告FS0064满足:这种结构导致
码为比由类型注释指示
较少通用的。该类型
变量T一直限制在
类''U'

warning FS0064: This construct causes code to be less generic than indicated by the type annotations. The type variable 'T has been constrained to be type ''U'.

错误FS0663::此类型参数有
在限制其
永远是'U'

error FS0663: This type parameter has been used in a way that constrains it to always be ''U'

错误FS0013的方式被使用:
型静态强制'U以'U结果
涉及对在此之前的计划
点信息的不确定类型的基于
。静态的强制不允许在某些类型的
。还需要进一步的类型
注释

error FS0013: The static coercion from type 'U to 'U
involves an indeterminate type based on information prior to this program point. Static coercions are not allowed on some types. Further type annotations are needed.

错误FS0661:一个或多个
明确的类或函数类型$的此绑定b $ b变量不能
一概而论,因为他们是
受限于其他类型的

error FS0661: One or more of the explicit class or function type variables for this binding could not be generalized, because they were constrained to other types

请解释我如何正确地改写上面,为什么我写了F#版本不编译。

Please, explain me how to correctly rewrite C# code above and why F# version I've wrote doesn't compiles.

推荐答案

本C#代码是不可能的F#。见如何翻译这C#代码(使用泛型类型约束)到F#的http:// CS .hubfs.net /论坛/线程/ 10534.aspx

This isn't possible in F#. See How do I translate this C# code (with generic type constraints) to F#? and http://cs.hubfs.net/forums/thread/10534.aspx.

这篇关于重写一些C#泛型代码为F#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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