上下文:我在 F# 中使用 .net/c#-library Fare,我尝试使用 eg Map.ofSeq
。Fare.State
由于不实现System.IComprable
接口 (FS0001) ,因此不支持比较失败。
在我的天真中,我试图添加interface IComparable
这样的内容:
type Fare.State with
interface IComparable<Fare.State> with
member this.CompareTo obj =
match box obj with
| :? Fare.State as other -> this.Id.CompareTo other.Id
| _ -> invalidArg "obj" "not a State"
然而,这是不可能的,因为 F# 要求实现的接口应在类型的初始声明中声明 (FS0909)。
我想到了以下解决方法:
- 引入包含 a
Fare.State
作为其唯一属性并实现的包装器类型IComparable
- 存储 ID 而不是实际的 ID,
Fare.State
并在需要的地方使用 Map 转换为实际状态 - 使用一些技巧添加
interface IComparable
到现有类型。
如果第三个选项不可能,那么哪个选项最合适?还有其他选择吗?