因此,我认为先投射表示形式"然后重新调整单位"是可以的,但是我不知道您是如何首先获得具有不同表示形式的值的,因为通常将这些表示形式固定在域中(例如,在任何地方都使用float.(无论如何,我都很喜欢您的floatMeasure函数,该函数从表示形式方面取消了单元方面的混淆,因此,如果您只需要更改表示形式,则可以直接表达它)If we define a unit of measure like:[<Measure>] type sand then an integer with a measurelet t = 1<s>and then convert it to a floatlet r = float twe see that r = 1.0 without a measure type. This seems very odd, as all the measure information has been lost.You can use LanguagePrimitives.FloatWithMeasure to convert back to a float with something likelet inline floatMeasure (arg:int<'t>) : (float<'t>) = LanguagePrimitives.FloatWithMeasure (float arg)which enforces the right types, but this doesn't feel like the right solution as the docs for units of measure (http://msdn.microsoft.com/en-us/library/dd233243.aspx) say However, for writing interoperability layers, there are also some explicit functions that you can use to convert unitless values to values with units. These are in the Microsoft.FSharp.Core.LanguagePrimitives module. For example, to convert from a unitless float to a float, use FloatWithMeasure, as shown in the following code.Which seems to suggest that the function should be avoided in F# code.Is there a more idiomatic way to do this? 解决方案 (Caveat: I've not used units much in anger.)I think that the only negative for using e.g. FloatWithMeasure is the unit-casting aspect (unitless to unitful). I think this is conceptually orthogonal to the numeric-representation-casting aspect (e.g. int to float). However there is (I think) no library function to do numeric-representation-casting on unit-ful values. Perhaps this is reflective of the fact that most unitful values model real-world continuous values, as so discrete representations like int are typically not used for them (e.g. 1<s> feels wrong; surely you mean 1.0<s>).So I think it's fine to 'cast representations' and then 'readjust units', but I wonder how you got the values with different representations in the first place, as it's often typical for those representations to be fixed for a domain (e.g. use float everywhere).(In any case, I do like your floatMeasure function, which un-confounds the unit-aspect from the representation-aspect, so that if you do need to only change representation, you have a way to express it directly.) 这篇关于跨类型会话维护度量单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-31 07:52