换句话说,如果我想要一个完全泛型的函数,我如何确保数值类型之间的编译/运行时转换。
例如:
let f x = x + 1 // int -> int
由于1
,自动承担int
。
我目前的黑客是:
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
定义
如果你想要一个完全泛型的函数来向参数添加一个,我建议你使用LanguagePrimitives.GenericOne
:
let inline f x = x + LanguagePrimitives.GenericOne
请注意,您还需要内联函数,否则运算符(+)
不能是泛型的。