我试图测试一个对象是否等于一个对象列表中的某个给定的条件(名称相等),如果是,请不要将它添加到列表中,否则添加它。我必须使用带有这个签名的方法“static int Find(List c,Coffee x)”。如果在c中存在x,则查找在c中查找x并返回有效索引(即,0,1,...),否则返回-1。当我通过精确匹配时,我的等号方法似乎没有意识到名称是相同的。为什么是这样?这里是我的代码:确定两个对象是否相等
Coffee obv = new Coffee();
Decaf decafCoffee = null;
Regular regularCoffee = null;
List<Coffee> inventory = new List<Coffee>();
if (some sxpression)
{
decafCoffee = new Decaf(name, D, C, M);
find = obv.Find(inventory, decafCoffee);
if (find == -1)
{
inventory.Add(decafCoffee);
}
}
public class Coffee : IDisposable
{
public override bool Equals(object obj)
{
if (obj is Coffee)
{
bool isNameEqual = Name.Equals(this.Name);
return (isNameEqual);
}
return false;
}
public int Find(List<Coffee> c, Coffee x)
{
if (c.Equals(x))
{
return 0;
}
return -1;
}
}
名单永远等于一个咖啡对象。 –
CodeMonkeyKing
2013-04-29 17:17:46
'List'*** ***如何等于'Coffee'?也许是时候重温你的Find方法了?如果不提供在相同字段上工作的GetHashCode方法,重新定义相等性也是一个非常糟糕的想法。 –
spender
2013-04-29 17:17:56
*“在c中查找x”*“嗯,不,不。它只是检查'c.Equals(x)'。因为“x”是类型“Coffee”,“c”是类型“列表”,它们不会相同。 –
RBarryYoung
2013-04-29 17:20:17