Effective C# 学习笔记(七) 重载GetHashCode()方法要小心

重载GetHashCode()方法的三原则

  1. 两个对象若相等,则其hashCode应该也是相等的,否则像Dictionary<K,T>这样的容器类型就无法使用hashCode作为Key去找到对应的对象
  2. 调用同一对象的GetHashCode()方法,永远返回相同的值
  3. hash函数对输入值的运算结果应随机分布在所有整型数字中。

 

ValueType类型(如:struct)总是使用其结构中的第一个字段的HashCode作为其的HashCode

 

若使用引用类型作为容器的hash键值,并重载GetHashCode()方法以提高获取hash值的效率,可以如下做:

 

public class Customer

{

private string name;

private decimal revenue;

public Customer(string name)

{

this.name = name;

}

public string Name

{

get { return name; }

// Name is readonly

}

public decimal Revenue

{

get { return revenue; }

set { revenue = value; }

}

public override int GetHashCode()

{

return name.GetHashCode();

}

public Customer ChangeName(string newName)

{

return new Customer(newName) { Revenue = revenue };

}

}

 

//测试

Customer c1 = new Customer("Acme Products");

myDictionary.Add(c1, orders);

// Oops, the name is wrong:

Customer c2 = c1.ChangeName("Acme Software");

Order o = myDictionary[c1];

原文地址:https://www.cnblogs.com/haokaibo/p/2096965.html