我想将 setter 属性添加到有区别的工会,我应该怎么做?
费:
type Factor =
| Value of Object
| Range of String
let mutable myProperty = 123
member this.MyProperty
with get() = myProperty
and set(value) = myProperty <- value
我想将 setter 属性添加到有区别的工会,我应该怎么做?
费:
type Factor =
| Value of Object
| Range of String
let mutable myProperty = 123
member this.MyProperty
with get() = myProperty
and set(value) = myProperty <- value
以下是我可能会采用的方法:
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。
为什么不使用类和活动模式:
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)
这显然会慢得多,但它可以让你做你想做的事
我对 F# 还不太熟悉,但我想你不能这样做,这没有任何意义。从他们的名字可以看出,受歧视的工会是工会。它们代表了某种选择。你正试图将一些状态融入其中。你想达到什么目的?用例是什么?
也许您需要做的就是为您的 DU 添加额外的“参数”,即如果您有
type DU =
| A of int
| B of string
并且您想添加 int 类型的 setter,那么您可以通过以下方式扩展 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)