У меня есть тип для уровней ведения журнала:
type LoggingLevel =
| Trace
| Debug
| Info
Я хотел бы сказать, что некоторые уровни ведения журнала выше, чем другие.Например, Trace
выше Info
.
Итак, я реализовал IComparable
так:
[<StructuralEqualityAttribute>]
[<CustomComparisonAttribute>]
type LoggingLevel =
| Trace
| Debug
| Info
interface IComparable<LoggingLevel> with
override this.CompareTo other =
let score x =
match x with
| Trace -> 0
| Debug -> 1
| Info -> 2
(score this) - (score other)
Но когда я пытаюсь его использовать, я получаю ошибку:
if a >= b
then
// ...
тип 'LoggingLevel' не поддерживает ограничение 'сравнение'.Например, он не поддерживает интерфейс System.IComparable
Как я тут ошибся?
Мне удалось заставить его работать, но теперь определение типа настолько многословно!Должен быть лучший способ ...
[<CustomEquality>]
[<CustomComparisonAttribute>]
type LoggingLevel =
| Trace
| Debug
| Info
override this.Equals (obj) =
match obj with
| :? LoggingLevel as other ->
match (this, other) with
| (Trace, Trace) -> true
| (Debug, Debug) -> true
| (Info, Info) -> true
| _ -> false
| _ -> false
override this.GetHashCode () =
match this with
| Trace -> 0
| Debug -> 1
| Info -> 2
interface IComparable<LoggingLevel> with
member this.CompareTo (other : LoggingLevel) =
let score x =
match x with
| Trace -> 0
| Debug -> 1
| Info -> 2
(score this) - (score other)
interface IComparable with
override this.CompareTo other =
(this :> IComparable<LoggingLevel>).CompareTo (other :?> LoggingLevel)