首页 > 解决方案 > F# 转换为文字运行时提供的类型

问题描述

换句话说,如果我想要一个完全通用的函数,我如何确保数字类型之间的编译/运行时转换。

例如:

let f x = x + 1 // int -> int

由于. int_1

我目前的黑客攻击是:

let gettype (x:'T) = typeof<'T>  // 'T -> Type
let one x = Convert.ChangeType (1, (gettype x))  // 'a -> obj
let f x = x + one(x) // obj -> obj

但这不起作用,因为+没有为objs定义

标签: f#type-conversion

解决方案


如果您想要一个向参数添加一个的完全通用函数,我建议您使用LanguagePrimitives.GenericOne

let inline f x = x + LanguagePrimitives.GenericOne

请注意,您还需要内联您的函数,因为否则运算符(+)不能是通用的。


推荐阅读