0

判別共用体にセッター プロパティを追加したいのですが、どのようにすればよいですか?

フェ:

type Factor =    
    | Value     of Object
    | Range     of String

    let mutable myProperty = 123
    member this.MyProperty
        with get() = myProperty
        and set(value) = myProperty <- value
4

3 に答える 3

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

次のように使用します。

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."

FsEye の時計モデル: http://code.google.com/p/fseye/source/browse/tags/2.0.0-beta1/FsEye/WatchModel で、あなたと同様のシナリオでこの手法を使用しました。 fs

于 2012-06-09T14:30:18.820 に答える
2

クラスとアクティブなパターンを使用しない理由:

type _Factor =    
    | Value_     of obj
    | Range_     of string

type Factor(arg:_Factor) =

    let mutable myProperty = 123
    member this._DU = arg
    member this.MyProperty
        with get() = myProperty
        and set(value) = myProperty <- value

let (|Value|Range|) (arg:Factor) = 
    match arg._DU with
    |Value_(t) -> Value(t)
    |Range_(t) -> Range(t)

これは明らかに大幅に遅くなりますが、やりたいことができます

于 2012-06-09T08:16:58.523 に答える
1

私はまだ F# にあまり詳しくありませんが、これはできないと思います。意味がありません。差別された組合は、その名前からわかるように組合です。それらはある種の選択を表しています。そして、それに何らかの状態を取り込もうとしています。何を達成しようとしていますか?ユースケースは何ですか?

おそらく必要なのは、DU に追加の「パラメータ」を追加することだけです。

type DU = 
    | A of int
    | B of string

int 型のセッターを追加したい場合は、次のように DU を拡張できます。

type DU = 
    | A of int * int
    | B of string * int

    member x.Set i =
        match x with
        | A(a1, a2) -> A(a1, i)
        | B(b1, b2) -> B(b1, i)
于 2012-06-09T08:19:45.703 に答える