Have you tried removing an object from a set and this object remains in this set? The world is big, and there is no wonder. A slight negligence will lead to this strange phenomenon. Now let's see what this "undead" object is like.
1. "undead" Object Appearance
This problem was initially raised by a colleague of mine. to reproduce the "undead" object, the code is simplified as follows:
// Code #01
Ilist products = new list <product> ();
Products. Add (getproduct ("1412 "));
Products. Remove (getproduct ("1412 "));
The product class code is as follows:
// Code #02
Class Product
{
Public Product (string ID)
{
M_id = ID;
}
Private string m_id;
Public String ID
{
Get {return m_id ;}
}
Public override string tostring ()
{
Return "ID:" + m_id;
}
}
The getproduct method reads data from the database based on the input ID and returns the data. Its signature is as follows:
// Code #03
Public static product getproduct (string ID );
To determine whether to remove an object numbered 1412 from products, add the following line at the end of code #01:
// Code #04
Console. writeline (products. Count );
2. accidentally fall into the trap
I don't know if you have the habit of viewing the SDK. In fact, the SDK contains a lot of information that inspires us to solve the problem. Now let's see if the SDK can find any clues.
Because the real body of products is list <t>, it is necessary to see how list <t> implements ilist. Remove:
This method determines equality using the default equality comparer equalitycomparer. Default for t, the type of values in the list.
Originally, list <t> used equalitycomparer. Default in ilist. Remove to determine whether two objects are equal. So how does equalitycomparer. Default know whether two objects are equal?
The default property checks whether type T implements the system. iequatable generic interface and if so returns an equalitycomparer that uses that implementation. otherwise it returns an equalitycomparer that uses the overrides of object. equals and object. gethashcode provided by T.