具有.NET的Equals和GetHashCode辅助方法的库

本文关键字:方法 NET Equals 具有 GetHashCode | 更新日期: 2023-09-27 18:21:52

GoogleGuava提供了很好的助手来实现equalshashCode,如下例所示:

public int hashCode() {
  return Objects.hashCode(lastName, firstName, gender);
}

有类似的Microsoft.NET库吗?

具有.NET的Equals和GetHashCode辅助方法的库

我不明白你为什么需要一个。如果你想为3个不同的项目创建一个基于默认GetHashCode的哈希代码,那么只需使用:

Tuple.Create(lastName, firstName, gender).GetHashCode()

这将归结为:

int h1 = lastName.GetHashCode();
int h2 = firstName.GetHashCode();
int h3 = gender.GetHashCode();
return (((h1 << 5) + h1) ^ (((h2 << 5) + h2) ^ h3));

对于这样一个通用的组合来说,这是非常合理的。

同样:

Tuple.Create(lastName, firstName, gender).Equals(Tuple.Create(lastName2, firstName2, gender2))

可以归结为调用:

return ((lastName == null && lastName2 == null) || (lastName != null && lastName.Equals(lastName2)))
  && ((firstName == null && firstName2 == null) || (firstName != null && firstName.Equals(lastName2)))
  && ((gender == null && gender2 == null) || (gender != null && gender.Equals(lastName2)));

再说一遍,和你所期望的一样好。

AFAIK none。然而,编写自己的代码不应该太复杂(nb使用Bernstein散列的变体):

public static class Objects
{
  public static bool Equals<T>(T item1, T item2, Func<T, IEnumerable<object>> selector)
  {
    if (object.ReferenceEquals(item1, item2) return true;
    if (item1 == null || item2 == null) return false;
    using (var iterator1 = selector(item1).GetEnumerator())
    using (var iterator2 = selector(item2).GetEnumerator())
    {
      var moved1 = iterator1.MoveNext();
      var moved2 = iterator2.MoveNext();
      if (moved1 != moved2) return false;
      if (moved1 && moved2)
      {
        if (!Equals(iterator1.Current, iterator2.Current)) return false;
      }
    }
    return true;
  }
  public static bool Equals(object item1, object item2)
  {
    return object.Equals(item1, item2);
  }
  public static int GetHashCode(params object[] objects) 
  {
    unchecked
    {
      int hash = 17;
      foreach (var item in objects)
      {
        hash = hash * 31 + item.GetHashCode();
      }
      return hash;
    }
  }
}