5

这是目标代码:

public class DlpItem : IEqualityComparer<DlpItem>
{   
    public string Text { get; set; }
    public int Id { get; set; }

    public DlpItem(int pId)
    {
        Text = string.Empty;
        Id = pId;
    }

    public override bool Equals(object obj)
    {
        return Id == (obj as DlpItem).Id;
    }

    public bool Equals(DlpItem a, DlpItem b)
    {
        return a.Id == b.Id;
    }

    public int GetHashCode(DlpItem item)
    {
        return Id.GetHashCode();
    }
}

我有两个列表如下:

var list1 = new List<DlpItem>();
list1.Add(new DlpItem(1));
list1.Add(new DlpItem(2));


var list2 = new List<DlpItem>();
list2.Add(new DlpItem(1));
list2.Add(new DlpItem(2));

var delItems = list1.Except(list2).ToList<DlpItem>();

delItems 始终包含两个项目。我在这里想念什么?

编辑:代码现在实现 IEquatable

public class DlpItem : IEqualityComparer<DlpItem>, IEquatable<DlpItem>
{   
    public string Text { get; set; }
    public int Id { get; set; }


    public override bool Equals(object obj)
    {
        return Id - (obj as DlpItem).Id == 0;
    }

    public bool Equals(DlpItem a, DlpItem b)
    {
        return a.Id == b.Id;
    }

    public bool Equals(DlpItem item)
    {
        return item != null && Id == item.Id;
    }

    public int GetHashCode(DlpItem item)
    {
        return Id.GetHashCode();
    }
}
4

1 回答 1

4

在您的示例中,您实际上并没有添加任何内容list2......一个足够简单的错误,但还有一个更重要的问题:

它必须IEquatable<T>不是IEqualityComparer<T>; 此外,您可能希望确保哈希码不会更改;最简单的方法是Id只读:

public class DlpItem : IEquatable<DlpItem>
{
    public string Text { get; set; }
    private readonly int id;
    public int Id { get { return id; } }

    public DlpItem(int id)
    {
        Text = "";
        this.id = id;
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as DlpItem);
    }

    public bool Equals(DlpItem other)
    {
        return other != null && this.Id == other.Id;
    }
    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}
于 2011-03-25T19:46:59.070 回答