• 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];

  • 相关阅读:
    hibernate中many-to-one的not-found属性和@notfound注解
    使用excel中的数据快速生成sql语句
    maven的生命周期
    单点登录(sso)入门
    sql server生成随机id
    javascript时间戳与日期格式的相互转换
    前后端分离的概念
    idea中maven项目打jar包
    [na][win]AD域组策略wifi自动配置
    [na]mail收发过程
  • 原文地址:https://www.cnblogs.com/haokaibo/p/2096965.html
Copyright © 2020-2023  润新知