types - F# 强制转换/将自定义类型转换为原始类型

标签 types casting f# primitive

我已经使用自定义 F# 类型设计了我的应用程序域,但是现在当我想将数据实际用于各种任务时,这些自定义类型似乎将成为 PITA...即将值写入 CSV 文件,使用其他库依赖原语等。

例如,我有一个这样的自定义类型(用作其他较大类型的构建块):

type CT32 = CT32 of float

但是这样的代码不起作用:
let x = CT32(1.2)
let y = float x //error: The type "CT32" does not support a conversion...
let z = x.ToString() //writes out the namespace, not the value (1.2)

我尝试使用 box/unbox 和 Convert.ToString() 以及两个 F# 转换运算符,但它们似乎都不允许我访问我的类型包含的基本原始值。有没有一种简单的方法来获取自定义类型中的原始值,因为到目前为止,它们比实际有用更令人头疼。

最佳答案

添加对 float 的支持很简单:

type CT32 = CT32 of float with
    static member op_Explicit x =
        match x with CT32 f -> f

let x = CT32(1.2)
let y = float x

关于types - F# 强制转换/将自定义类型转换为原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30602535/

相关文章:

types - 单数据类型与双数据类型

javascript 对象属性类型仅接受数字

c++ - Boost phoenix值和函数返回值类型

c - 如何将指针变量移动指定字节数?

c# - 使用 'as' 进行转换 - 为什么这不起作用?

exception - 异步抛出异常

node.js - puppeteer 类型 node_modules/puppeteer/lib/types "' has no exported member ' Cookie'

c++ - 类型转换运算符总是模棱两可

F#使用GetEnumerator时无法枚举yield生成的序列

.net - F#-解析日期