简体   繁体   English

带有Equals的库和用于.NET的GetHashCode帮助器方法

[英]Library with Equals and GetHashCode helper methods for .NET

Google Guava provides nice helpers to implement equals and hashCode like the following example demonstrates: Google Guava为实现equalshashCode提供了很好的帮助,如下例所示:

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

Is there a similar library for Microsoft .NET? 是否有类似的Microsoft .NET库?

I don't see why you'd need one. 我不明白为什么你需要一个。 If you want to create a hash-code based on the default GetHashCode for 3 different items, then just use: 如果您想基于3个不同项的默认GetHashCode创建哈希码,那么只需使用:

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

That'll boil down to the equivalent of: 这将归结为相当于:

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

Which is pretty reasonable for such a general-purpose combination. 对于这种通用组合来说,这是非常合理的。

Likewise: 同样:

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

Would boil down to the equivalent of calling: 归结为相当于调用:

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)));

Again, about as good as you could expect. 再次,大约和你期望的一样好。

AFAIK none. AFAIK没有。 However, writing your own shouldn't be too complex (nb using a variation of the Bernstein hash): 但是,编写自己的应该不会太复杂(使用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;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM