星期四, 12月 07, 2006

實作Equals method以及equality operator需遵守的規則

MSDN上提到:

The following rules outline the guidelines for implementing the Equals method and the equality operator (==):


  1. Implement the GetHashCode method whenever you implement the Equals method. This keeps Equals and GetHashCode synchronized.


  2. Override the Equals method whenever you implement the equality operator (==), and make them do the same thing. This allows infrastructure code such as Hashtable and ArrayList, which use the Equals method, to behave the same way as user code written using the equality operator.


  3. Override the Equals method any time you implement the IComparable Interface.


  4. Consider implementing operator overloading for the equality (==), not equal (!=), less than (<), and greater than (>) operators when you implement IComparable.


  5. Do not throw exceptions from the Equals or GetHashCode methods or the equality operator (==).

有空再來探討其背後的原因