How to best implement Equals for custom types?

前端 未结 10 702
春和景丽
春和景丽 2020-11-28 08:41

Say for a Point2 class, and the following Equals:

public override bool Equals ( object obj )

public bool Equals ( Point2 obj )

This is the

10条回答
  •  温柔的废话
    2020-11-28 09:10

    The simple and best way to override Equals looks like:

    public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
    
            public override bool Equals(object other)
            {
                Person otherItem = other as Person;
    
                if (otherItem == null)
                    return false;
    
                return Age == otherItem.Age && Name == otherItem.Name;
            }
            public override int GetHashCode()
            {
                int hash = 13;
                hash = (hash * 7) + Age.GetHashCode();
                hash = (hash * 7) + Name.GetHashCode();
                return hash;
            }
        }
    

    Override the GetHashCode method to allow a type to work correctly in a hash table.

提交回复
热议问题