The trygetvalue method is very commonly used. You can convert the "judgment key existence" and "according to the key value" steps into one step. In this way, the hash value of the key is calculated only once, which is very efficient. Note that the idictionary interface does not define trygetvalue, while the generic interface idictionary <t, V> defines trygetvalue. The keyedcollection type inherits from the collection type <t>, and the collection <t> inherits from the icollection interface <t>. The reason should be that keyedcollection is not just a dictionary, but also a linear table. Therefore, keyedcollection does not have trygetvalue by default.
However, keyedcollection has a protected member: dictionary attribute. A generic idictionary is returned to represent the internal dictionary. Therefore, you can call the trygetvalue of the internal idictionary to rewrite the keyedcollection.
For example, first define a simple type: student. The ID attribute is the member key.
Class student
{
Public int ID {Get; set ;}
Public string name {Get; set ;}
}
Keyedcollection is defined as follows:
// + Using system. Collections. objectmodel;
Class mykeyedcollection: keyedcollection <int, student>
{
// Auxiliary Addition Method
Public void add (int id, string name)
{
Add (new student () {id = ID, name = Name });
}
// Rewrite the abstract method: getkeyforitem
Protected override int getkeyforitem (student item)
{
Return item. ID;
}
// Explicitly define the trygetvalue of the protected idictionary
Public bool trygetvalue (INT key, out student value)
{
Return dictionary. trygetvalue (Key, out value );
}
}
Sample Code:
VaR DIC = new mykeyedcollection ();
Dic. Add (3, "Martin ");
Dic. Add (1, "Tony ");
Dic. Add (2, "Liu ");
Student st;
If (DIC. trygetvalue (1, out st ))
Console. writeline (St. Name );
Else
Console. writeline ("not found ");
Output:
Tony