F#使用自定义类进行设置 [英] F# Set using custom class

查看:64
本文介绍了F#使用自定义类进行设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Set操作与我拥有的类一起使用.此类的每个实例都有一个唯一的ID.我是否需要实现System.IComparable接口,如果需要,该怎么办?

I'm trying to use Set operations with a class that I have. Every instance of this class has a unique ID. Do I need to implement the System.IComparable interface and if so how would I?

type SomeClass(id : int) =
    member this.ID = id

let someSet = Set.of_list [SomeClass(1); SomeClass(2)]
let test = someSet.Contains(SomeClass(2))    

推荐答案

以下是应该有效的实现:

Here's an implementation that should work:

type SomeClass(id : int) =    
    member this.ID = id
    override this.Equals(o) =
        match o with
        | :? SomeClass as sc -> this.ID = sc.ID
        | _ -> false
    override this.GetHashCode() =
        id.GetHashCode()
    interface System.IComparable with
        member this.CompareTo(o) =
            match o with
            | :? SomeClass as sc -> compare this.ID sc.ID
            | _ -> -1

这篇关于F#使用自定义类进行设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆