简体   繁体   English

使用.GetHashCode()的对象相等性列表

[英]List of objects equality using .GetHashCode()

I would like to understand how the GetHashCode method works on lists of objects for equality. 我想了解GetHashCode方法如何在具有相等性的对象列表上工作。 Given this example: 给出以下示例:

var user1 = new User { Id = Guid.NewGuid().ToString(), Name = "Chris" };
var user2 = new User { Id = Guid.NewGuid().ToString(), Name = "Jeff" };

var userList1 = new List<User> { user1, user2 }.OrderBy(o => o.Id);
var userList2 = new List<User> { user1, user2 }.OrderBy(o => o.Id);

var usersList1Hash = userList1.GetHashCode();
var usersList2Hash = userList2.GetHashCode();

var userListsEqual = usersList1Hash == usersList2Hash; // false

var userList1Json = JsonConvert.SerializeObject(userList1);
var userList2Json = JsonConvert.SerializeObject(userList2);

var usersList1JsonHash = userList1Json.GetHashCode();
var usersList2JsonHash = userList2Json.GetHashCode();

var userListsJsonEqual = usersList1JsonHash == usersList2JsonHash; // true
  1. Why are the lists of objects not equal when comparing the hash codes? 比较哈希码时,为什么对象列表不相等

  2. Why are the list of objects equal when serializing to JSON strings and comparing the hash codes? 序列化为JSON字符串并比较哈希码时,为什么对象列表相等

GetHashCode function gives signed int32 hash of an object. GetHashCode函数提供对象的带符号的int32哈希。

From MSDN. 从MSDN。

Two objects that are equal return hash codes that are equal. 相等的两个对象返回相等的哈希码。 However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes. 但是,事实并非如此:相等的哈希码并不意味着对象相等,因为不同的(不相等)对象可以具有相同的哈希码。

GetHashCode is a virtual function and can be overridden. GetHashCode是一个虚拟函数,可以被覆盖。 What you get after calling JsonConvert.SerializeObject function a string. 在将JsonConvert.SerializeObject函数调用为字符串后会得到什么。 string class has its own implementation of GetHashCode which is based on contents of a string. string类具有自己的GetHashCode实现,该实现基于字符串的内容。 Something like below. 像下面这样。 That's why it matches. 这就是为什么匹配。

public class string {  
  char[] str = null;
  ...
  public string(char[] input) {
    this.str = input;
  }

  public override GetHashCode() {
    //Logic to convert str to int 32 based on string contents;

    return Convert.ToInt32(str);
  }
}

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

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