我想定义一个度量类型
[<Measure>] type kB
它将显式转换为int时的字节数转换为:
(int)7<kB> // would result 1024kB - explicit would be fine
由于无法将显式转换运算符添加到类似于C#的类型中,所以我陷入了困境。有人有主意吗?更好的方法是一个隐式转换,这样当一个函数需要字节数时,它可以被调用如下
Allocate(7<kB>) // implicit would be superfine
特殊的转换函数不需要上诉--编写kB函数很简单,但没有那么好:
let kB(n) = 1024 * n
kB(7)
7 |> kB
对单位进行同样操作的转换函数也是不酷的。
7<kB> |> convertToByte
发布于 2015-08-25 03:58:22
活动模式对你来说“酷”够了吗?
[<Measure>] type kB
// single case active pattern to convert from kB to raw B value
let (|Bytes|) (x : int<kB>) = int(x * 1024)
// use pattern matching in the declaration
// val printBytes : int<kB> -> unit
let printBytes (Bytes(b)) =
printfn "It's %d bytes" b
printBytes 7<kB>
// "It's 7168 bytes"
发布于 2015-08-25 04:58:31
对你问题的简短回答似乎是否定的。这让我觉得像add一样,因为这个转换有点变化。唉,按照“编程f# 3.0”第108页的规定,静态方法如何?
[<Measure>]
type B =
static member toKB (x: int<B>) =
1<KB> * x / 1024<B>
and [<Measure>] KB =
static member toB (x: int<KB>) =
x * 1024<B> / 1<KB>
let b1 = 1024<B>
let kb1 = B.toKB b1
https://stackoverflow.com/questions/32169761
复制相似问题