• 21 GetHashCode Equels ReferenceEquals的比较


     
    //GetHashCode方法,一般是获取Hash值,不同的Hash值,一定是不同的两个对象,
    //相同的hash值有可能是同一个对象。hash值类似于索引代表其唯一性。
    //一般GetHashCode方法不单独使用或者不常使用。讲对象作为hashtable或dictionary的key
    //时才会用到,当插入key时,首先会调用 GethashCode方法判断是否存在,如果存在,会在调用
    //Equels方法判断这两个对象是否相等。所以一般 GethashCode方法和Equels方法配合使用
    // 重写Equels方法一般也要重写GetHashCode方法
    // ReferenceEquals 比较两个对象的引用
    string sq = "123";
    string sw = "123";
    // 对于String 类型 因为重写了Equels方法,所以实际比较的是两个字符串的值,所以以下返回True
    Console.WriteLine(sq.Equals(sw));
    Console.WriteLine(sq == sw);
    
    Student student = new Student() { Name = "zheng", Age = 12 };
    Student student1 = new Student() { Name = "zheng", Age = 12 };
    Console.WriteLine(String.ReferenceEquals(student, student));
    student.Name = "111";
    Console.WriteLine(String.ReferenceEquals(student, student));
    Hashtable hashtable = new Hashtable();
    
    hashtable.Add(student, "11");
    hashtable.Add(student1, "11");
    

      

     public class Student
        {
    
            public String Name { get; set; }
    
            public int Age { get; set; }
            public override bool Equals(object obj)
            {
                Student student = obj as Student;
                return this.Name == student.Name && this.Age == student.Age;
            }
            public override int GetHashCode()
            {
                
                return this.Age;
            }
        }
    

      

  • 相关阅读:
    寻找水王
    学习进度条(第十一周)
    学习进度条(第十周)
    学习进度条(第九周)
    团队项目:个人工作总结10
    团队项目:个人工作总结09
    团队项目:个人工作总结08
    深度学习之--深度置信网络DBN
    神经网络学习之----受限玻尔兹曼机RBM(代码实现)
    神经网络学习之----受限玻尔兹曼机RBM
  • 原文地址:https://www.cnblogs.com/hnzheng/p/12089730.html
Copyright © 2020-2023  润新知