Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么不能使用removed方法删除genereic列表中的项目?_C#_.net_Generics_List - Fatal编程技术网

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;

哦,听起来好像有人有周一的案子咪咪,办公室