我正在尝试重新引用解除引用(!)和赋值(:=)运算符,但不是全局运算符。我仍然希望保持通常的ref op重载。这里有一些代码来说明问题:
type MyVar<'a>(init:'a) =
let mutable _value = init
member __.Get() = _value
member __.Set x = _value <- x
//static member (!) (s:MyVar<'a>) = s.Get() // compiles, doesn't work
//static member (:=) (d:MyVar<'a>, s) = d.Set(s) // warning, doesn't work
//let inline (!) (x :MyVar<'a>) = x.Get() // overrides !ref
//let inline (:=) (x :MyVar<'a>) (v :'a) = x.Set(v) // overrides ref := v
let inline (!!) (x :MyVar<'a>) = x.Get() // works but ugly
let inline (.=) (x :MyVar<'a>) (v :'a) = x.Set(v) // works ... meh
let test_myvar() =
let mv = new MyVar<_>("wee")
let r = ref 100
let x = !mv
let y = !!mv
let z = !r
mv .= "haaa"
r := 42
解决方案:
@ Carsten的解决方案正是我所寻求的&amp;作品。然而,事实证明我正在使用Websharper,它使用Quotations进行编译,而@Carstens解决方案变得有点more complex。由于Websharper.UI.Next包含该解决方案,我所需要的只是包含在我的项目中,并且它可以工作!
答案 0 :(得分:5)
您可以通过重复onCreate()
和(!)
运算符来尝试使用static constraints:
(:=)
我删除了您的访问者,因为我只需要与type MyVar<'a>(init:'a) =
let mutable _value = init
member __.Value with get () = _value and set v = _value <- v
let inline (!) a =
(^a : (member Value : ^b) a)
let inline (:=) a v =
(^a : (member Value : ^b with set) (a, v))
相同(但您可以重新添加)
这是一个F#-interactive会话,用你的价值证明这一点:
Ref<'a>
<强>备注强>
我不确定我是否真的会这样做 - 你只是重新发明val mv : MyVar<string>
val r : int ref = {contents = 100;}
> !mv;;
val it : string = "wee"
> !r;;
val it : int = 100
> mv := "It works";;
val it : unit = ()
> !mv;;
val it : string = "It works"
> r := 50;;
val it : unit = ()
> !r;;
val it : int = 50
- 细胞(作为一个班级)并且什么也得不到,当然它可能很难为其他人阅读 - 所以请对待在意。