我在 Microsoft 文档中找到了以下内容:
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 code
我进行了自己的测试以了解该方法:
public static void HashMetod()
{
List<Cliente> listClientTest = new List<Cliente>
{
new Cliente { ID = 1, name = "Marcos", Phones = "2222"}
};
List<Empresa> CompanyList = new List<Empresa>
{
new Empresa { ID = 1, name = "NovaQuimica", Clients = listClientTest },
new Empresa { ID = 1, name = "NovaQuimica", Clients = listClientTest }
};
CompanyList.Add(CompanyList[0]);
foreach (var item in CompanyList)
{
Console.WriteLine("Hash code = {0}", item.GetHashCode());
}
Console.WriteLine("CompanyList[0].Equals(CompanyList[1]) = {0}", CompanyList[0].Equals(CompanyList[1]));
Console.WriteLine("CompanyList[0].Equals(CompanyList[2]) = {0}", CompanyList[0].Equals(CompanyList[2]));
}
我的问题是:两个不同的对象如何返回相同的 HashCode?我相信如果两个对象返回相同的值,它们就是 Equals(这就是我的方法所显示的)。执行我的方法并检查一下。