简体   繁体   中英

Warning: Object defines operator == or operator != but does not override Object.Equals(object o)

I'm programming in C# Unity and have really annoying problem - I want to define special Pair class with following relations:

public class Pair<T1>{
    public int First;
    public T1 Second;

    public bool Equals(Pair<T1> b){
        return First == b.First;
    }

    public static bool operator==(Pair<T1> a, Pair<T1> b){
        return a.First == b.First;
    }   
    public static bool operator!=(Pair<T1> a, Pair<T1> b){
        return a.First != b.First;
    }
}

Which gives me following warning:

Warning CS0660: 'Pair' defines operator == or operator != but does not override Object.Equals(object o) (CS0660) (Assembly-CSharp)

But also when I spawn two objects of Pair type with same First integer, their == operator returns True (as I want). When I only declare Equals function, same == operator returns False value (I understand that somehow Unity compares their addressees in memory), with no warnings. Is there any method to avoid warnings and still get True value of == operator?

Just override that method to make the compiler happy :

public override bool Equals(object o)
{
   if(o == null)
       return false;

   var second = o as Pair<T1>;

   return second != null && First == second.First;
}

public override int GetHashCode()
{
    return First;
}

The method you created is a custom equals method, you need to override that of the object class (which is used in the == && != operators)

You need to override the Equal :

public override bool Equals(object obj)
{
    if (ReferenceEquals(null, obj)) return false;
    if (ReferenceEquals(this, obj)) return true;
    if (obj.GetType() != this.GetType()) return false;
        return Equals((Pair<T1>) obj);
}

And the GetHashCode method:

public override int GetHashCode()
{
    unchecked
    {
        return (First*397) ^ EqualityComparer<T1>.Default.GetHashCode(Second);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM