We will discuss the necessary conditions for using a custom class as a collection class key.
The sortedlist data structure is a linked list, and the key value is stored after sorting. To obtain the value corresponding to a key value, you only need to perform the comparison operation. Therefore, to use a custom class as the key, you must implement the int compareto (Object OBJ) method in the icomparable interface.
For example
Sortedlist <selfclass, string> List = new sortedlist <selfclass, string> (3 );
List. Add (New selfclass (1), "apple ");
List. Add (New selfclass (2), "orange ");
List. Add (New selfclass (3), "Pear ");
MessageBox. Show (list [New selfclass (2)]);
The keys of a dictionary are hashed and stored. Each time a key-value pair is added, the gethashcode method in the key object is called. For example, I have defined a selfclass, as follows:
Public class selfclass: icomparable
{
Public selfclass (int I)
{
This. Index = I;
}
Public int compareto (Object OBJ)
{
If (obj. GetType ()! = This. GetType ())
{
Return-1;
}
Selfclass selfobj = OBJ as selfclass;
Int result = 0;
If (this. index> selfobj. Index)
{
Result = 1;
}
If (this. index <selfobj. Index)
{
Result = 1;
}
Return result;
}
Public override bool equals (Object OBJ)
{
If (obj. GetType ()! = This. GetType ())
{
Return false;
}
Selfclass Other = OBJ as selfclass;
If (this. Index! = Other. Index)
{
Return false;
}
Return true;
}
Public int Index = 0;
Public override string tostring ()
{
Return this. Index. tostring ();
}
Public override int gethashcode ()
{
Return this. Index. tostring (). gethashcode ();
}
}
Use the custom class above to create a dictionary <selfclass, string>:
Dictionary <selfclass, string> List = new dictionary <selfclass, string> (3 );
List. Add (New selfclass (1), "apple"); // call the gethashcode Method
List. Add (New selfclass (2), "orange"); // call the gethashcode method.
List. Add (New selfclass (3), "Pear"); // call the gethashcode method.
MessageBox. Show (list [New selfclass (2)]); // call the gethashcode method and then call the bool equals (Object OBJ) method.
Hashtable:
Hashtable ht = new hashtable (3 );
Ht. Add (New selfclass (1), "apple ");
Ht. Add (New selfclass (2), "orange ");
Ht. Add (New selfclass (3), "Pear ");
MessageBox. Show (HT [New selfclass (2)]. tostring ());
Therefore, if your custom class wants to support keys used as sortedlist, dictionary, and hashtable at the same time, implement the icomparable interface. Rewrite bool equals (Object OBJ) and override int gethashcode () and the string tostring () method. Of course, the tostring method is not required.
If you have any questions, you can debug them.