F#构造函数和类:为每个成员属性设置没有额外可变变量的类

时间:2013-11-21 05:28:48

标签: f#

所以我一直在MSDN上查看有关F#中构造函数的this页面。 我正在查看第一个代码示例

type MyClass(x0, y0, z0) =
    let mutable x = x0
    let mutable y = y0
    let mutable z = z0
    do
        printfn "Initialized object that has coordinates (%d, %d, %d)" x y z
    member this.X with get() = x and set(value) = x <- value
    member this.Y with get() = y and set(value) = y <- value
    member this.Z with get() = z and set(value) = z <- value
    new() = MyClass(0, 0, 0)

有没有办法在没有可变的let绑定的情况下为你拥有的每个属性设置它?

我在问,因为我的课有很多变数。更糟糕的是,我正在考虑增加更多方式。

这是一个例子。

    type lineSet (x1off,x2off,y1off,y2off,x1,x2,y1,y2,rot,rotOff,count) =
        member x1Offset with get() = x10ff and set(value) = x1Offset <- value
        member x2Offset with get() = x20ff and set(value) = x2Offset <- value
        member y1Offset with get() = y10ff and set(value) = y1Offset <- value
        member y2Offset with get() = y20ff and set(value) = y2Offset <- value

        member x1Start with get() =x1Start and set(value) = x1Start <- value
        member x2Start
        member y1Start
        member y2Start

        member rotation
        member rotationOffset

        member lineCount
        member SVG_Representation
        member XAML_Representation

必须为这些属性中的每一个添加可变的let绑定将是非常不优选的。它本质上是我班级变量数量的两倍。

是否有某种简化语法可以让构造函数将其所有参数分配给相应的属性?

此外,这行代码:

   member x1Offset with get() = x10ff and set(value) = x1Offset <- value

不会产生任何错误。话虽如此,我不确定它是否符合我的希望。

1 个答案:

答案 0 :(得分:2)

您可以使用此语法

type MyClass(property1 : int) =
    member val Property1 = property1
    member val Property2 = "" with get, set

取自this page