内置“ >比较“不能与“IComparable< T>”工作 [英] Built-in "< > compare" doesn't work with "IComparable<T>"?
本文介绍了内置“ >比较“不能与“IComparable< T>”工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个歧视联盟,我希望使用内置的运算符> <比较最大
。
I have a Discriminated Union, and I hope to use built in operators like > < compare max
for it.
[<CustomComparison>]
type SymbolType =
| A
| B
| C
| D
interface IComparable<SymbolType> with
member x.CompareTo y =
match x, y with
| A, A-> 0
| A, _ -> 1
| _, A-> -1
| _, _ -> 0
我理解我可以使用 IComparable
但是我必须做一个 null
检查,更糟的是,我必须像(SymbolType)y
I understand I can use IComparable
, but then i have to do a null
check, what's worse is that I have to cast it like (SymbolType) y
which I assume would be time consuming.
推荐答案
您可以使用薄型包装器实现所需的方法:
You can just implement the required methods with thin wrappers:
[<CustomComparison>]
[<CustomEquality>]
type SymbolType =
| A
| B
| C
| D
override x.Equals y =
match y with
| :? SymbolType as t -> (((x :> IComparable<_>).CompareTo) t)=0
| _ -> false
interface IComparable with
member x.CompareTo y =
match y with
| :? SymbolType as t -> ((x :> IComparable<_>).CompareTo) t
| _ -> failwith "bad comparison"
interface IComparable<SymbolType> with
member x.CompareTo y =
match x, y with
| A, A-> 0
| A, _ -> 1
| _, A-> -1
| _, _ -> 0
这样可避免重复输入。
这篇关于内置“ >比较“不能与“IComparable< T>”工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文