我有这门课.
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 ListfooList = new List (); 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 (item => item.Id == id) .FirstOrDefault (); 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应该解决这个问题?
return otherObj == null && otherObj.Id == this.Id;
那是对的吗?不应该
return otherObj != null && otherObj.Id == this.Id;