C#重写Equals和GetHashCodeC#基础学习

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace day01
 8 {
 9     class Class31
10     {
11         static void Main(string[] args)
12         {
13             Student stu1 = new Student("zhangsan", 23);
14             Student stu2 = new Student("zhangsan", 23);
15             Console.WriteLine(stu1.Equals(stu2));
16             Console.ReadKey();
17         }
18     }
19     public class Student
20     {
21         private string name;
22         private int age;
23         public string Name { get; set; }
24         public int Age { get; set; }
25         public Student(string name,int age)
26         {
27             Name = name;
28             Age = age;
29         }
30         public override string ToString()
31         {
32             return "name: " + Name + " age: " + Age;
33         }
34         //public override bool Equals(object obj)
35         //{
36         //    if(obj == null)
37         //    {
38         //        return false;
39         //    }
40         //    if(obj.GetType() == typeof(Student))
41         //    {
42         //        Student stu = (Student)obj;
43         //        if(stu.Name.Equals(this.Name) && stu.Age == this.Age)
44         //        {
45         //            return true;
46         //        }
47         //        else
48         //        {
49         //            return false;
50         //        }
51         //    }
52         //    else
53         //    {
54         //        抛出异常
55         //        throw new ArgumentException("类型转换异常");
56         //    }
57         //}
58         public override bool Equals(object obj)
59         {
60             if(obj == null)
61             {
62                 return false;
63             }
64             if(obj is Student)
65             {
66                 Student stu = obj as Student;
67                 if(stu.Name.Equals(this.Name) && stu.Age == this.Age)
68                 {
69                     return true;
70                 }
71                 else
72                 {
73                     return false;
74                 }
75             }
76             else
77             {
78                 throw new ArgumentException("类型转换异常");
79             }
80 
81         }
82         //如何重写GetHashCode()方法
83         //先放着
84         public override int GetHashCode()
85         {
86             return base.GetHashCode();
87         }
88     }
89 }

 

posted @ 2019-04-09 15:45  littlelittleprince  阅读(1195)  评论(0编辑  收藏  举报