2009-01-26 23 views
0

我有這堂課。爲什麼不使用Removed方法刪除生成列表中的項目?

public class Foo 
{ 
    public Guid Id { get; set; } 

    public override bool Equals(object obj) 
    { 
     Foo otherObj = obj as Foo; 

     return otherObj == null && otherObj.Id == this.Id; 
    } 

    public override int GetHashCode() 
    { 
     return this.Id.GetHashCode(); 
    } 
} 

你可以看到我覆蓋了這個對象的Equals和GetHashCode。

我現在運行的代碼

// Create Foo List 
List<Foo> fooList = new List<Foo>(); 

fooList.Add(new Foo { Id = Guid.NewGuid()}); 
fooList.Add(new Foo { Id = Guid.NewGuid()}); 
fooList.Add(new Foo { Id = Guid.NewGuid()}); 
fooList.Add(new Foo { Id = Guid.NewGuid()}); 
fooList.Add(new Foo { Id = Guid.NewGuid()}); 

// Keep Id of last Create 
Guid id = Guid.NewGuid(); 

fooList.Add(new Foo { Id = id }); 

Console.WriteLine("List Count {0}", fooList.Count); 

// Find Foo in List 
Foo findFoo = fooList 
    .Where<Foo>(item => item.Id == id) 
    .FirstOrDefault<Foo>(); 

if (findFoo != null) 
{ 
    Console.WriteLine("Found Foo"); 

    // Found Foo now I want to delete it from list 
    fooList.Remove(findFoo); 
} 

Console.WriteLine("List Count {0}", fooList.Count); 

當這個運行FOO下面的代碼片段被發現,但列表不刪除找到的項目。

這是爲什麼?我認爲重寫Equals和GetHashCode應該解決這個問題?

回答

8
return otherObj == null && otherObj.Id == this.Id; 

這是正確的嗎?它不應該是

return otherObj != null && otherObj.Id == this.Id; 
+0

這正是錯誤。非常感謝。愚蠢的錯誤。 – 2009-01-26 21:24:37

相關問題