f# - 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
但这不起作用,因为+
没有为obj
s定义
解决方案
如果您想要一个向参数添加一个的完全通用函数,我建议您使用LanguagePrimitives.GenericOne
:
let inline f x = x + LanguagePrimitives.GenericOne
请注意,您还需要内联您的函数,因为否则运算符(+)
不能是通用的。
推荐阅读
- ios - 为什么 .gitignore 文件中不包含 ios/build 文件夹?
- apache-nifi - PutBigQueryBatch 处理器抛出异常:BasicClientConnManager 的使用无效:连接仍然分配
- c# - 从父表单到第二表单的下拉 ValueMember 为 %
- junit - 为什么我的一些 Junit 课程没有运行?
- javascript - 当两个条之间的范围内时,我的 p:barChart 中缺少一个条。我用谷歌搜索了很多,请回答我或更新有关此的任何线索
- c++ - std::filesystem::relative() 在 Windows 上部分现有路径上的行为不正确
- python - 如何在 Python 中从 Windows 句柄加载图像
- react-native - 错误消息:任务:app:installDebug FAILED
- php - 使用 php ajax 来自不同输入字段的多个图像
- flutter - 如何将编码的结果重写为字符串表示?