为什么F#中的CustomEquality和CustomComparison有两种不同的语法?

为什么F#中的CustomEquality和CustomComparison有两种不同的语法?,f#,comparison,equality,F#,Comparison,Equality,我想在F#中实现一个类型Symbol,它有一个关联的字符串和位置(比如文本中的行号)。我会这样做: type Symbol = Symbol of string * int // (string, line number) [<CustomEquality; CustomComparison>] type Symbol = | Symbol of string * int member x.GetString() = match x with

我想在F#中实现一个类型
Symbol
,它有一个关联的字符串和位置(比如文本中的行号)。我会这样做:

type Symbol = Symbol of string * int // (string, line number)
[<CustomEquality; CustomComparison>]
type Symbol =
    | Symbol of string * int
    member x.GetString() =
        match x with
        | Symbol (s, _) -> s
    override x.Equals(y) = // Equality only compares strings, not positions.
        match y with
        | :? Symbol as i -> i.GetString() = x.GetString()
        | _ -> false
     override x.GetHashCode() =
        match x with
        | Symbol (s, p) -> hash (s, p)
我想要一个自定义等式,该等式将取消行号。我将有一个考虑行号的“严格等式”,但我希望默认等式只比较字符串。现在看来,我们必须做到以下几点:

type Symbol = Symbol of string * int // (string, line number)
[<CustomEquality; CustomComparison>]
type Symbol =
    | Symbol of string * int
    member x.GetString() =
        match x with
        | Symbol (s, _) -> s
    override x.Equals(y) = // Equality only compares strings, not positions.
        match y with
        | :? Symbol as i -> i.GetString() = x.GetString()
        | _ -> false
     override x.GetHashCode() =
        match x with
        | Symbol (s, p) -> hash (s, p)

为什么我可以写
重写x.Equals(y)…
,但不能写
重写x.CompareTo(yobj)…
?为什么我必须指定
接口System.I可与…
比较?似乎存在一个
系统。IEquatable
,但我不需要指定它,为什么?这并不是很大的区别,但我只是想知道为什么会有这种区别。

区别在于,对于Equals,您重写了Object.Equals,它是基类上的一个虚拟方法,而对于CompareTo,您实现了一个接口(在F#中,它需要通过“interface..with”显式实现)