如何将setter添加到F#中有区别的联合

nhu*_*lin 0 f# properties discriminated-union

我想为有区别的工会添加setter属性,我该怎么做呢?

FE:

type Factor =    
    | Value     of Object
    | Range     of String

    let mutable myProperty = 123
    member this.MyProperty
        with get() = myProperty
        and set(value) = myProperty <- value
Run Code Online (Sandbox Code Playgroud)

Ste*_*sen 5

这是我如何处理它:

type Value = { value: obj; mutable MyProperty: int }
type Range = { range: string; mutable MyProperty: int }

type Factor =    
    | Value     of Value
    | Range     of Range

    member this.MyProperty
        with get() = 
            match this with
            | Value { MyProperty=myProperty }
            | Range { MyProperty=myProperty } -> myProperty
        and set(myProperty) = 
            match this with
            | Value x -> x.MyProperty <- myProperty
            | Range x -> x.MyProperty <- myProperty
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

let v = Value {value="hi":>obj ; MyProperty=0 }
v.MyProperty <- 2

match v with
| Value { value=value } as record ->
    printfn "Value of value=%A with MyProperty=%i" value record.MyProperty
| _ -> 
    printfn "etc."
Run Code Online (Sandbox Code Playgroud)

我在类似的场景中使用了这种技术,在FsEye的手表模型中得到了满意的结果:http://code.google.com/p/fseye/source/browse/tags/2.0.0-beta1/FsEye/WatchModel. fs.