1

我有实体类:

    [Serializable, Class(Table = "mon.tableView", Lazy = false)]
    public class TableView
    {
    [CompositeId(1)]
    [KeyProperty(2, Name = "column1", Column = "column1", TypeType = typeof(int))]
    [KeyProperty(3, Name = "column2", Column = "column2", TypeType = typeof(int))]
    internal int VirtualId { get; set; }

    [Property(Column = "column1")]
    private int column1 { get; set; }

    [Property(Column = "column2")]
    public int? column2 { get; set; }

    [Property(Column = "column3")]
    public int column3 { get; set; }

    [Property(Column = "otherColumn")]
    public string otherColumn{ get; set; }

    public override bool Equals(object other)
    {
        if (this == other)
            return true;

        TableViewv dp = other as TableView;

        if (vdp == null)
            return false; // null or not a ReadOnlyUserRole

        return column1.Equals(vdp.column1) ^ column2.Equals(vdp.column2) && column3.Equals(vdp.column3) && otherColumn.Equals(vdp.otherColumn);        }

    public override int GetHashCode()
    {
        return column1.GetHashCode() ^ column2.GetHashCode();
    }
}

我知道 GetHashCode() 给出 2 个答案: - 当 2 个对象不相等时,我们知道它们不相等。- 当 2 个对象相等时,它们可能相等,但不确定。因此有 Equal() 方法。

GetHashCode() 方法为我提供了 2 个对象的相同整数,但我知道其他属性不相等。当我得到这些对象的列表时,我有几次重复的对象,我的问题是何时调用 Equals() 方法?因为调用此方法时,我从未在调试模式下看到过。

4

1 回答 1

0

您的 GetHashCode 实现看起来正确,但您的 equals 似乎有问题,您应该只比较复合键 column1 和 column2 的值(可为空):

public override bool Equals(object other)
{
    if (this == other)
        return true;

    TableViewv dp = other as TableView;

    if (vdp == null)
        return false; // null or not a ReadOnlyUserRole


    return column1 == vdp.column1 &&
            ( (!column2.HasValue && !vdp.column2.HasValue ) || (column2.HasValue && vdp.column2.HasValue && column2.Value == vdp.column2.Value ));    
}
于 2013-05-22T13:11:39.550 回答