F#测量单位,不丢失测量类型的铸造 [英] F# Unit of Measure, Casting without losing the measure type
问题描述
是否有内置版本的类型转换函数保留单位,如果不是我将如何使他们?因此,例如,使用这个代码如何将intWithSecondsMeasure转换为浮点数,而不会丢失度量或乘以 1.0< s>
?
Is there built in version of the type casting functions that preserves units and if not how would I make them? So for example with this code how would I cast intWithSecondsMeasure to a float without losing the measure or multiplying by 1.0<s>
?
[<Measure>] type s
let intWithSecondsMeasure = 1<s>
let justAFloat = float intWithSecondsMeasure
推荐答案
由@kvb提供肯定工作,但我不想使用 unbox
运算符进行此转换。有一个更好,内置的方式,我认为应该编译为一个NOP到IL(我没有检查,但是unbox可能会最终作为一个 unbox
在IL中的指令,因此添加一个运行时类型检查。)
The answer provided by @kvb certainly works, but I'd prefer not to use the unbox
operator for this conversion. There's a better, built in way that I think should be compiled as a NOP to IL (I haven't checked but unbox is probably going to end up as a unbox
instruction in IL and thus adds a runtime type check).
在F#中进行单位转换的首选方法是 LanguagePrimitives。 TypeWithMeasure
( MSDN )
The preferred way to do unit conversions in F# is LanguagePrimitives.TypeWithMeasure
(MSDN).
let inline float32toFloat (x:float32<'u>) : float<'u> =
x |> float |> LanguagePrimitives.FloatWithMeasure
这篇关于F#测量单位,不丢失测量类型的铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!