c# How to find if two objects are equal

前端 未结 6 1945
北荒
北荒 2020-12-08 02:40

I want to know the best way to compare two objects and to find out if they\'re equal. I\'m overriding both GethashCode and Equals. So a basic class looks like:



        
6条回答
  •  無奈伤痛
    2020-12-08 03:33

    For any two objects, object equality implies hash code equality, however, hash code equality does not imply object equality. From Object.GetHashCode on MSDN:

    A hash function must have the following properties:

    If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.

    In other words, your Equals is written wrong. It should be something like:

    public override bool Equals(object obj)
    {
        Test other = obj as Test;
        if (other == null)
            return false;
    
        return (Value == other.Value)
            && (String1 == other.String1)
            && (String2 == other.String2);
    }
    

    GetHashCode is good for collections (like Dictionary) to quickly determine approximate equality. Equals is for comparing if two objects really are the same.

提交回复
热议问题