CompareTo( )
is implemented by
MyClass
:
public int CompareTo(object obj) {
return Val - ((MyClass) obj).Val;
}
Because the parameter to
CompareTo( )
must be of type
object
,
obj
must be explicitly cast
to
MyClass
in order for
Val
to be accessed. However, it’s precisely this type of thing that
generics were designed to eliminate!
To solve this problem, C# provides a generic version of
IComparable
, which is declared
like this:
public interface IComparable
In this version, the type of data being compared is passed as a type argument to
T
. This
causes the declaration of
CompareTo( )
to be changed, as shown next:
int CompareTo(T
obj
)
Now, the parameter to
CompareTo( )
can be specified as the proper type and no cast from
object
is needed.
IComparable
is also implemented by all built-in types.
Here is an improved version of
MyClass
that implements
IComparable
:
// This version of MyClass implements IComparable
class MyClass : IComparable {
public int Val;
www.freepdf-books.com
Do'stlaringiz bilan baham: |