使用标准化单元类型来保持兼容性
例如,SI 单位的类型已在 ti#1 中的 F#核心库中标准化。打开相应的子命名空间 UnitNames
或 UnitSymbols
,以使用它们。或者,如果只需要几个 SI 单位,则可以使用类型别名导入它们:
/// Seconds, the SI unit of time. Type abbreviation for the Microsoft standardized type.
type [<Measure>] s = Microsoft.FSharp.Data.UnitSystems.SI.UnitSymbols.s
有些用户倾向于执行以下操作,只要定义已经可用,就不应该这样做 :
/// Seconds, the SI unit of time
type [<Measure>] s // DO NOT DO THIS! THIS IS AN EXAMPLE TO EXPLAIN A PROBLEM.
当与引用标准 SI 类型的其他代码接口时,差异变得明显。引用标准单元的代码是兼容的,而定义自己类型的代码与不使用其特定定义的任何代码不兼容。
因此,始终使用 SI 单位的标准类型。你是否参考 UnitNames
或 UnitSymbols
并不重要,因为这两个中的等同名称指的是相同的类型:
open Microsoft.FSharp.Data.UnitSystems.SI
/// This is valid, since both versions refer to the same authoritative type.
let validSubtraction = 1.<UnitSymbols.s> - 0.5<UnitNames.second>