簡體   English   中英

帶有Equals的庫和用於.NET的GetHashCode幫助器方法

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

Google Guava為實現equalshashCode提供了很好的幫助,如下例所示:

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

是否有類似的Microsoft .NET庫?

我不明白為什么你需要一個。 如果您想基於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沒有。 但是,編寫自己的應該不會太復雜(使用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