【发布时间】:2013-04-29 17:12:05
【问题描述】:
我正在尝试测试一个对象是否等于给定条件(名称相等)的对象列表中的一个,如果是,则不要将其添加到列表中,否则添加它。我必须使用具有此签名“static int Find(List c, Coffee x)”的方法。 Find 在 c 中查找 x 并返回有效索引(即 0、1、...),如果 x 存在于 c 中,否则返回 -1。当我传递完全匹配时,我的 equals 方法似乎没有意识到名称是相同的。为什么是这样?这是我的代码:
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;
}
}
【问题讨论】:
-
List
永远不会等于 Coffee 对象。 -
List<Coffee>永远怎么能等于Coffee?也许是时候重新审视您的Find方法了?在不提供适用于相同字段的 GetHashCode 方法的情况下重新定义相等性也是一个非常糟糕的主意。 -
"Find seeks x in c .." 嗯,不是的。它只是检查是否
c.Equals(x)。因为 "x" 是Coffee类型,而 "c" 是List<Coffee>类型,它们不会相等。