2012-01-26 14 views
2

私はF#で匿名クラスをインスタンス化し、自分自身のハッシュ/等価性を定義したいと考えています。誰か私に教えてもらえますか?F#の匿名クラス

インターフェイスでEquals/GetHashCodeを指定しても機能しません。メソッドをインスタンス化することは可能ですが、どのような方法でも呼び出すことはできません。基本的には、指定されたハッシュ関数を持つオブジェクトを私に与える方法で、以下のインタフェースIBlahをインスタンス化したいと思います。私が得ることができる最も近いのは、testfixtureの関数 "instance"ですが、それはデフォルトハッシュを使用するインスタンスとインスタンスを生成します。

また、クラスimplで "inner" 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 

答えて

12

あなたはGetHashCodeを上書きするために、あなたのオブジェクト式に最初の型としてobjSystem.Object)を指定する必要があります。

type IBlah = 
    abstract anint : int 

let blah = 
    { new obj() with 
     override x.GetHashCode() = 0 
    interface IBlah with 
     member x.anint = 0 } 
関連する問題