You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

F#中SN类型标注CustomEquality等属性报FS0377错误的原因咨询

自定义比较与相等属性的类类型报错解析

报错的类类型代码

[<CustomComparison; CustomEquality>]
type SN () =        
    interface IComparable<SN> with
        member this.CompareTo other = failwith ""            
    interface IComparable with
        member this.CompareTo obj = failwith ""
    interface IEquatable<SN> with
        member this.Equals other = failwith ""
    override this.Equals obj = failwith ""
    override this.GetHashCode () = failwith ""

编译时抛出错误:Error FS0377 This type uses an invalid mix of the attributes 'NoEquality', 'ReferenceEquality', 'StructuralEquality', 'NoComparison' and 'StructuralComparison'

正常运行的联合类型代码

[<CustomEquality;CustomComparison>]
type DU =
    | L    
    override x.Equals(yobj) = failwith ""
    override x.GetHashCode() = failwith ""
    interface System.IComparable with
        member x.CompareTo yobj = failwith ""

问题原因

这是F#编译器的历史bug:当类同时实现IComparable<T>泛型接口与CustomComparison/CustomEquality属性时,编译器会错误地自动推断启用了结构比较/相等属性,这与显式标注的自定义属性产生冲突,进而抛出错误。

而联合类型(DU)不存在这个错误推断逻辑,因此可以正常编译。该bug后续已被修复。

旧版本编译器临时解决办法

可以显式添加NoStructuralEquality和NoStructuralComparison属性,抵消编译器的错误推断:

[<CustomComparison; CustomEquality; NoStructuralEquality; NoStructuralComparison>]
type SN () =        
    interface IComparable<SN> with
        member this.CompareTo other = failwith ""            
    interface IComparable with
        member this.CompareTo obj = failwith ""
    interface IEquatable<SN> with
        member this.Equals other = failwith ""
    override this.Equals obj = failwith ""
    override this.GetHashCode () = failwith ""

内容的提问来源于stack exchange,提问作者citykid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 02:23:14