2

For this class definition:

type Foo(f1: int, f2: string) =
member x.F1 = f1
member x.F2 = PostProcess f2

Will PostProcess (some string manipulation function) gets called every time f2 is accessed? If the answer is yes and I want to avoid it, what’s the right idiom? Is this one below recommended? It is a bit too verbose for me.

type Foo =
val F1: int
val F2: string

new (f1, f2) as this = 
    {F1 = f1; F2 = f2;}
    then this.F2 = PostProcess(f2) |> ignore
4

2 回答 2

6

在您的原始定义F2中是一个只读属性,PostProcess每次访问时都会调用该函数。这很容易验证:

let PostProcess s = printfn "%s" s; s

type Foo(f1: int, f2: string) =
  member x.F1 = f1
  member x.F2 = PostProcess f2

let f = Foo(1,"test")
let s1 = f.F2
let s2 = f.F2

以下是我如何编写只处理一次的类:

type Foo(f1: int, f2: string) =
  let pf2 = PostProcess f2
  member x.F1 = f1
  member x.F2 = pf2
于 2010-02-19T19:22:12.397 回答
1

是的,每次都会重新评估属性(例如,就像getC# 中的属性)。

有关您的特定问题的简洁答案,请参阅@kvb 的答案。

一般来说,参见例如

http://msdn.microsoft.com/en-us/library/dd233192(VS.100).aspx

http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!894.entry

有关编写类构造函数的最佳方法的语言信息。简明扼要的总结是,您应该使用“主构造函数”(正如您所拥有的,紧跟在类型名称后面的括号,带有构造函数参数),然后在类的顶部使用let和作为构造函数主体。do

于 2010-02-19T19:26:26.010 回答