如何将此扩展方法转换为扩展属性?

时间:2013-07-30 18:57:15

标签: f#

我有一个扩展方法

type System.Int32 with
    member this.Thousand() = this * 1000

但它需要我这样写

(5).Thousand()

我想摆脱两个括号,从使它成为属性而不是方法(为了学习的缘故),我该如何将它作为属性?

3 个答案:

答案 0 :(得分:7)

Jon的答案是一种方法,但对于只读属性,还有一种更简洁的方式来编写它:

type System.Int32 with
    member this.Thousand = this * 1000

此外,根据您的偏好,您可能会发现写5 .Thousand(注意额外空间)比(5).Thousand更令人满意(但您不能只做5.Thousand },甚至5.ToString())。

答案 1 :(得分:3)

我真的不知道F#(可耻!)但基于this blog post,我希望:

type System.Int32 with  
    member this.Thousand 
      with get() = this * 1000

怀疑不会将你从第一组括号中解放出来(否则F#可能尝试将整个事物解析为文字),但它应该有所帮助你是第二个。

就个人而言,我不会将这种事情用于“生产”扩展,但它对于处理大量值的测试代码很有用。

特别是,我发现在日期周围有扩展方法很简单,例如19.June(1976)是一种非常简单易读的构建测试数据的方法。但不适用于生产代码:)

答案 2 :(得分:2)

它并不漂亮,但如果你真的想要一个适用于任何数字类型的功能,你可以这样做:

let inline thousand n =
  let one = LanguagePrimitives.GenericOne
  let thousand = 
    let rec loop n i =
      if i < 1000 then loop (n + one) (i + 1)
      else n
    loop one 1
  n * thousand

5.0 |> thousand
5 |> thousand
5I |> thousand