PART II
C h a p t e r 2 1 :
E x p l o r i n g t h e S y s t e m N a m e s p a c e
659
Object
Object
is the class that underlies the C#
object
type. The members of
Object
were discussed
in Chapter 11, but because of its central role in C#, its methods are repeated in Table 21-16
for your convenience.
Object
defines one constructor, which is shown here:
public Object( )
It constructs an empty object.
The IComparable and IComparable Interfaces
Many classes will need to implement either the
IComparable
or
IComparable
interface
because it enables one object to be compared to another by various methods defined by the
.NET Framework. Chapter 18 introduced the
IComparable
and
IComparable
interfaces,
where they were used to enable two objects of a generic type parameter to be compared. They
were also mentioned in the discussion of
Array
, earlier in this chapter. However, because of
their importance and applicability to many situations, they are formally examined here.
IComparable
is especially easy to implement because it consists of just this one method:
int CompareTo(object
v
)
This method compares the invoking object against the value in
v.
It returns greater than zero
if the invoking object is greater than
v,
zero if the two objects are equal, and less than zero if
the invoking object is less than
v.
Method
Purpose
public vir tual bool Equals(object
ob
)
Returns true if the invoking object is the same
as the one referred to by
object.
Returns false
other wise.
public static bool Equals(object
ob1
, object
ob2
)
Returns true if
ob1
is the same as
ob2.
Returns
false other wise.
protected Finalize( )
Per forms shutdown actions prior to garbage
collection. In C#,
Finalize( )
is accessed through
a destructor.
public vir tual int GetHashCode( )
Returns the hash code associated with the
invoking object.
public Type GetType( )
Obtains the type of an object at runtime.
protected object Member wiseClone( )
Makes a “shallow copy” of the object. This
is one in which the members are copied, but
objects referred to by members are not.
public static bool ReferenceEquals(object
ob1
,
object
ob2
)
Returns true if
ob1
and
ob2
refer to the same
object. Returns false other wise.
public vir tual string ToString( )
Returns a string that describes the object.
T
ABLE
21-16
Methods Defi ned by
Object
www.freepdf-books.com
660
P a r t I I :
E x p l o r i n g t h e C # L i b r a r y
The generic version of
IComparable
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
)
Here, the type of data that
CompareTo( )
operates on can be explicitly specified. This
makes
IComparable
type-safe. For this reason,
IComparable
is now preferable
to
Do'stlaringiz bilan baham: |