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 }

 

转载于:https://www.cnblogs.com/littlelittleprince/p/10677346.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值