C# 为什么不能使用removed方法删除genereic列表中的项目?
我有这门课C# 为什么不能使用removed方法删除genereic列表中的项目?,c#,.net,generics,list,C#,.net,Generics,List,我有这门课 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 GetHash
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应该可以解决这个问题
return otherObj == null && otherObj.Id == this.Id;
对吗?难道不是吗
return otherObj != null && otherObj.Id == this.Id;
哦,听起来好像有人有周一的案子咪咪,办公室