我有这门课。
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应该解决这个问题吗?
答案 0 :(得分:8)
return otherObj == null && otherObj.Id == this.Id;
这是对的吗?不应该是
return otherObj != null && otherObj.Id == this.Id;