WebSharper:opaque类型,检查`===`的相等性

时间:2013-05-27 15:36:25

标签: f# websharper

我需要一个在F#中完全不透明的数据类型,其中使用JS ===定义了相等性。 WebSharper手册说我应该覆盖Equals,但我不能使它工作。

let x : OpaqueType = X<_>

let f (y : OpaqueType) =
    if x = y then // this line should be translated to `if (x === y)`
        42
    else
        10

那么,OpaqueType的正确定义是什么?

当然,我可以使用obj并添加内联函数x === y,但我想要更精彩的内容。

1 个答案:

答案 0 :(得分:2)

我会选择这样的事情:

module Test =
    open IntelliFactory.WebSharper

    [<JavaScript>]
    let Counter = ref 0

    [<Sealed>]
    [<JavaScript>]
    type T() =

        let hash =
            incr Counter
            Counter.Value

        [<JavaScript>]
        override this.GetHashCode() =
            hash

        [<JavaScript>]
        override this.Equals(other: obj) =
            other ===. this


    [<JavaScript>]
    let Main () =
        let a = T()
        let b = T()
        JavaScript.Log(a, b, a = b, a = a, hash a, hash b)

.NET库(例如,在Dictionary中使用)期望平等和散列是一致的。它们还通过虚拟方法与类型相关联,因此内联将无法正常工作。上面的代码为您提供了一个类似于引用的相等语义的类型。