pea*_*ach 2 c# containers contains equals iequatable
我正在使用a System.Collections.Generic,其中包含我编写的类的实例.
我已经读过collections .Contains方法使用object.Equals(),或者Equals()从IEquatable接口中实现该方法.
我已经覆盖了对象方法,以及从界面实现.但是,Queue.Contains(instance)总是返回false.我究竟做错了什么?
例如...
class Foo : IEquatable<Foo>
{
...
int fooField1;
...
public override bool Equals(object obj)
{
Foo other = obj as Foo;
bool isEqual = false;
if (other.fooField1 == this.fooField1)
{
isEqual = true;
}
return isEqual;
}
public bool Equals(Foo other)
{
bool isEqual = false;
if (other.fooField1 == this.fooField1)
{
isEqual = true;
}
return isEqual;
}
}
...
void SomeFunction()
{
Queue<Foo> Q = new Queue<Foo>();
Foo fooInstance1 = new Foo();
Foo fooInstance2 = new Foo();
fooInstance1.fooField1 = 5;
fooInstance2.fooField1 = 5;
Q.Enqueue(fooInstanec1);
if(Q.Contains(fooInstance2) == false)
{
Q.Enqueue(fooInstance2);
}
}
Run Code Online (Sandbox Code Playgroud)
fooInstance2始终添加到队列中.实际上,当我在调试器上运行它时,永远不会达到Equals的实现.
我究竟做错了什么?
一旦初始编译错误被整理出来,您的示例代码就会按预期工作.并不是它与提出的问题相关,请阅读重写等于(您还需要覆盖GetHashCode并检查错误情况,如null/type-mismatch).
class Foo : IEquatable<Foo>
{
private int _fooField1;
public Foo(int value)
{
_fooField1 = value;
}
public override bool Equals(object obj)
{
return Equals(obj as Foo);
}
public bool Equals(Foo other)
{
return (other._fooField1 == this._fooField1);
}
}
class Program
{
static void SomeFunction()
{
var Q = new Queue<Foo>();
Foo fooInstance1 = new Foo(5);
Foo fooInstance2 = new Foo(5);
Q.Enqueue(fooInstance1);
if (!Q.Contains(fooInstance2))
{
Q.Enqueue(fooInstance2);
}
else
{
Console.Out.WriteLine("Q already contains an equivalent instance ");
}
}
static void Main(string[] args)
{
SomeFunction();
}
}
Run Code Online (Sandbox Code Playgroud)