换句话说,如果我想要一个完全通用的函数,如何确保数字类型之间的编译/运行时转换。
例如:
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
但这不起作用,因为未为+
定义obj
答案 0 :(得分:6)
如果您想要一个将参数添加一个的通用函数,建议您使用LanguagePrimitives.GenericOne
:
let inline f x = x + LanguagePrimitives.GenericOne
请注意,您还需要内联函数,因为否则操作符(+)
不能是通用的。