F#中的匿名类

时间:2012-01-26 17:40:30

标签: f#

我想在F#中实例化一个匿名类,并定义我自己的哈希/相等。有人可以告诉我怎么样?

在界面中指定Equals / GetHashCode不起作用。可以实例化这些方法,但不能以我能看到的任何方式调用它们。基本上,我想以一种给我一个具有指定哈希函数的对象的方式实例化下面的IBlah接口。我能得到的最接近的是testfixture中的函数“instance”,但是会生成使用默认哈希的实例。

我也想知道是否有人可以告诉我如何在类impl中调用“内部”GetHashCode。

非常感谢提前。

open NUnit.Framework

type IBlah =
    abstract anint : int
    abstract GetHashCode : unit -> int

type impl (i:int) =
    interface IBlah with
        member x.anint = i        
        member x.GetHashCode () = failwithf "invoked"
    //override x.GetHashCode () = i

[<TestFixture>]
type trivial () =

    let instance i =
        {
            new IBlah with
                member x.anint = i
                member x.GetHashCode () = failwith "It is invoked after all"
        }

    // this fails (in the comparison, not due to a failwith)
    [<Test>]
    member x.hash () =
        Assert.AreEqual (instance 1 |> hash, instance 1 |> hash)

    // this passes if the commented-out override is added, otherwise it fails due to different hashvalues
    [<Test>]
    member x.hash' () =
        Assert.AreEqual (impl 1 |> hash, impl 1 |> hash)

    // this passes whether the override is there or not (i.e. no exception is thrown either way)
    [<Test>]
    member x.hash'' () =
        impl 1 :> IBlah |> hash |> ignore

1 个答案:

答案 0 :(得分:12)

您需要指定objSystem.Object)作为对象表达式中的第一个类型来覆盖GetHashCode

type IBlah =
    abstract anint : int

let blah = 
  { new obj() with
      override x.GetHashCode() = 0
    interface IBlah with
      member x.anint = 0 }