Comparing two instances of a class

后端 未结 8 773
礼貌的吻别
礼貌的吻别 2020-12-03 17:33

I have a class like this

public class TestData
{
   public string Name {get;set;}
   public string type {get;set;}

   public List Members = ne         


        
8条回答
  •  我在风中等你
    2020-12-03 18:14

    There are three ways objects of some reference type T can be compared to each other:

    1. With the object.Equals method
    2. With an implementation of IEquatable.Equals (only for types that implement IEquatable)
    3. With the comparison operator ==

    Furthermore, there are two possibilities for each of these cases:

    1. The static type of the objects being compared is T (or some other base of T)
    2. The static type of the objects being compared is object

    The rules you absolutely need to know are:

    • The default for both Equals and operator== is to test for reference equality
    • Implementations of Equals will work correctly no matter what the static type of the objects being compared is
    • IEquatable.Equals should always behave the same as object.Equals, but if the static type of the objects is T it will offer slightly better performance

    So what does all of this mean in practice?

    As a rule of thumb you should use Equals to check for equality (overriding object.Equals as necessary) and implement IEquatable as well to provide slightly better performance. In this case object.Equals should be implemented in terms of IEquatable.Equals.

    For some specific types (such as System.String) it's also acceptable to use operator==, although you have to be careful not to make "polymorphic comparisons". The Equals methods, on the other hand, will work correctly even if you do make such comparisons.

    You can see an example of polymorphic comparison and why it can be a problem here.

    Finally, never forget that if you override object.Equals you must also override object.GetHashCode accordingly.

提交回复
热议问题