6

我正在使用 Entity Framework 5。在我的 C# 代码中,我想比较两个对象是否相等。如果没有,那么我想发布更新。

有人告诉我我需要重写 .Equals 方法,然后还要重写 gethascode 方法。我的课程如下所示:

public class Students    {
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int Age {get; set;} 
}

有人可以解释为什么我需要覆盖 .Equals 和 .GetHashCode。也有人可以给我一个例子。特别是我不确定哈希码。请注意,我的 PersonId 是此类的唯一编号。

4

2 回答 2

3

You need to override the two methods for any number of reasons. The GetHashCode is used for insertion and lookup in Dictionary and HashTable, for example. The Equals method is used for any equality tests on the objects. For example:

public partial class myClass
{
  public override bool Equals(object obj)
  {
     return base.Equals(obj);
  }

  public override int GetHashCode()
  {
     return base.GetHashCode();
  }
}

For GetHashCode, I would have done:

  public int GetHashCode()
  {
     return PersonId.GetHashCode() ^ 
            Name.GetHashCode() ^ 
            Age.GetHashCode();
  }

If you override the GetHashCode method, you should also override Equals, and vice versa. If your overridden Equals method returns true when two objects are tested for equality, your overridden GetHashCode method must return the same value for the two objects.

于 2013-08-11T04:44:11.920 回答
1

Classes are reference types. When you create two objects and store them in variables you're only storing the reference to them. This means if you attempt to compare them you will only be comparing two references which will only be equal if they're pointing to the same object on heap. If you want to change that behavior you will have to override Equals.
Also some collections depend on GetHashCode to store elements in tree-like(or any other) structures that need some means of comparison between two objects of a given class. Which is why you need to implement these methods if you need your defined class to behave correctly under the specified circumstances.
A typical implementation of GetHashCode would be the xor of class's fields which is given in @No Idea For Name's answer. But since PersonId is unique in your example, you could also use that:

public int GetHashCode()
{
   return PersonId.GetHashCode();
}
于 2013-08-11T04:45:14.767 回答