是否可以通过显式或隐式转换来定义kB,GB,...的度量单位? [英] Is it possible to define units of measure for kB, GB, ... with explicit or implicit conversion?

查看:91
本文介绍了是否可以通过显式或隐式转换来定义kB,GB,...的度量单位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个度量类型

[<Measure>] type kB

可在显式转换为int时转换为字节数:

that converts to the number of bytes when explicitly cast to an int:

(int)7<kB>   // would result 1024kB - explicit would be fine

由于无法将显式转换运算符添加到C#中的类型,因此我陷入了困境.有人有主意吗? 甚至更好的是隐式转换,这样,当一个函数需要一定数量的字节时,可以像

Since there is no way to add an explicit conversion operator to a type like in C#, I am stuck. Anyone has an idea? Even better would be an implicit conversion, so that when a function requires numbers of bytes, it can be called like

Allocate(7<kB>) // implicit would be superfine

特殊的转换函数没有吸引力-编写kB函数很简单,但效果却不那么好:

Special conversion functions do not appeal - writing a kB function is trivial but not as nice:

let kB(n) = 1024 * n
kB(7)
7 |> kB

与单位功能相同的转换函数也不酷

A conversion function that does the same with units is not cool either

7<kB> |> convertToByte

推荐答案

活动模式对您来说足够酷"吗?

Are active patterns "cool" enough for you?

[<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"

这篇关于是否可以通过显式或隐式转换来定义kB,GB,...的度量单位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆