.net - How to implement Multi-type IComparable / IEquatable in C# -
let have following class:
public sealed class scalevalue : icomparable, icomparable<scalevalue>, iequatable<scalevalue> { public double value { get; set;} public string definition { get; set;} // interface methods ... } if want make class comparable double should include icomparable<double> , implement way or have way?
and when want class comparable doubles should double.compareto give same result scalevalue.compareto?
and how equals?
i think put responsibilities wrong in design. think best option make scale class containsvalue(double value) method. way can value , keep responsibilities needed.
what class comparable you. make comparable anything, non-generic version of icomparable interface takes object; in implementation of compareto method, can sniff type of object (unless null).
when use generic version of icomparable<t>, you're making statement implement strongly-typed comparison method whatever type parameter t is.
generally, if have icomparable<t> implementation 1 type, probably should have iequatable<t> implementation well.
having icomparable/icomparable<t> implementation means being represented structure has natural ordering it. ordering implies there can equality between 2 instances: if instance a of t not greater or less instance b of t must equal.
to end, if implement icomparable/icomparable<t>, logic dictates implement iequatable/iequatable<t>.
of course, when implement iequatable/iequatable<t>, should override equals , gethashcode.
which in turn means should override comparison operators:
==(which implies!=)<,<=>,>=
Comments
Post a Comment