zoukankan      html  css  js  c++  java
  • 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];

  • 相关阅读:
    在VMware中使用Nat方式设置静态IP
    saltstack实现自动化扩容
    saltstack常用模块
    saltstack之nginx、php的配置
    桶排序
    【前端安全】JavaScript防http劫持与XSS
    memcached
    10 行 Python 代码写的模糊查询
    为什么print在python3中变成了函数?
    一行python代码实现树结构
  • 原文地址:https://www.cnblogs.com/haokaibo/p/2096965.html
Copyright © 2011-2022 走看看