[英]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:我在 C# Unity 中编程并且遇到了非常烦人的问题 - 我想定义具有以下关系的特殊 Pair 类:
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)
警告 CS0660:“Pair”定义运算符 == 或运算符 != 但不覆盖 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).但是,当我生成两个具有相同 First 整数的
Pair
类型对象时,它们的==
运算符返回True
(如我所愿)。 When I only declare Equals function, same ==
operator returns False
value (I understand that somehow Unity compares their addressees in memory), with no warnings.当我只声明 Equals 函数时,相同的
==
运算符返回False
值(我知道 Unity 以某种方式比较内存中的收件人),没有警告。 Is there any method to avoid warnings and still get True
value of ==
operator?是否有任何方法可以避免警告并仍然获得
==
运算符的True
值?
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)您创建的方法是自定义的 equals 方法,您需要覆盖对象类的方法(在 == && != 运算符中使用)
You need to override the Equal
:您需要覆盖
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:和
GetHashCode
方法:
public override int GetHashCode()
{
unchecked
{
return (First*397) ^ EqualityComparer<T1>.Default.GetHashCode(Second);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.