我想在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
Run Code Online (Sandbox Code Playgroud)
Dan*_*iel 12
您需要指定obj(System.Object)作为要覆盖的对象表达式中的第一个类型GetHashCode.
type IBlah =
abstract anint : int
let blah =
{ new obj() with
override x.GetHashCode() = 0
interface IBlah with
member x.anint = 0 }
Run Code Online (Sandbox Code Playgroud)