2013-04-29 172 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; 
} 
相關問題