2013-04-29 91 views
1

我试图测试一个对象是否等于一个对象列表中的某个给定的条件(名称相等),如果是,请不要将它添加到列表中,否则添加它。我必须使用带有这个签名的方法“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; 
    } 
     }   
+1

名单永远等于一个咖啡对象。 – CodeMonkeyKing 2013-04-29 17:17:46

+1

'List '*** ***如何等于'Coffee'?也许是时候重温你的Find方法了?如果不提供在相同字段上工作的GetHashCode方法,重新定义相等性也是一个非常糟糕的想法。 – spender 2013-04-29 17:17:56

+0

*“在c中查找x”*“嗯,不,不。它只是检查'c.Equals(x)'。因为“x”是类型“Coffee”,“c”是类型“列表”,它们不会相同。 – RBarryYoung 2013-04-29 17:20:17

回答

0

你的错误是在这里:

public int Find(List<Coffee> c, Coffee x) 
{ 
    if (c.Equals(x)) // <-- this will never return true 
    { 
     return 0; 
    } 

    return -1; 
} 

然而,你Find方法是不必要的。使用List<T>.IndexOf,让您的概念:

var index = inventory.IndexOf(decafCoffee); 
0

你的问题是在这里:

public int Find(List<Coffee> c, Coffee x) 
{ 
    if (c.Equals(x)) 
    { 
     return 0; 
    } 

    return -1; 
} 

cList<Coffee>不是Coffee对象。

你需要改变你的代码,以便它遍历列表,查看它是否包含x

for (int i = 0; i < c.Count; ++i) 
    if (c[i].Equals(x)) 
     return i; 

return -1 
2

您在列表测试的平等咖啡的一个实例。这将始终返回-1。你想要的是c.Contains(x)。请记住,当您覆盖Equals时,您还应该为GetHashCode()提供类似的覆盖。在这里寻找物体上的Microsoft advice on implementing and overriding Equals

public int Find(List<Coffee> c, Coffee x) { 
    return c.IndexOf(x); 
} 

public override int GetHashCode() 
{ 
    return Name == null ? 0 : Name.GetHashCode(); 
} 
0

你可以做如下,既然你有Equals方法,你可以用它来寻找匹配项

public int Find(List<Coffee> c, Coffee x) 
{ 
    if (c.Any(i=>i.Equals(x)) 
    { 
     return 0; 
    } 

    return -1; 
} 
相关问题