首页 文章

如何通过静态成员生成bool成员类型直接在Measure类型本身上生成?

提问于
浏览
3

如何在F#中创建一个具有静态成员New的度量类型,可以给出一个值并为bool生成给定的度量类型?

我有这个用于int,int64和decimal,它完美地工作 .

[<Measure>] type MyInt = static member New value = value * 1<MyInt>
    [<Measure>] type MyInt64 = static member New value = value * 1L<MyInt64>
    [<Measure>] type MyDecimal = static member New value = value * 1m<MyDecimal>

但这不起作用:

[<Measure>] type MyBool = static member New value = value * true<MyBool>

编译错误是 Unexpected token '>' or incomplete expression

我也用字符串和DateTime来运行它 . 我的目标是基本上使用Measure类型来提供编译时检查,而不会影响单例联合类型包装器的运行时性能 . (See this answer by Jack P. for reference.

理想情况下,我很乐意将这个概念用于我的所有类型,但我没有看到不是数字的类型 .

1 回答

  • 4

    因此,只有某些内置类型内置了度量类型定义

    从这些规格来看

    type float<[<Measure>] 'U>
    type float32<[<Measure>] 'U>
    type decimal<[<Measure>] 'U>
    type int<[<Measure>] 'U>
    type sbyte<[<Measure>] 'U>
    type int16<[<Measure>] 'U>
    type int64<[<Measure>] 'U>
    

    对于其他类型,您可以定义自己的类型 .

    对于数字类型,您可以使用 LanguagePrimitives.Int32WithMeasure 等编写 new 函数,这对于浮点数实际上要快一些 . 我认为最近其他数字类型已经过优化,所以在编译时全部乘以1 .

相关问题