2023-11-04
自我提升
0

Program.cs

c#
using System; namespace Equals判断相等 { class Program { static void Main(string[] args) { //ToString Equals Object int a = 12; int b = 34; Console.WriteLine(a.Equals(b));// 值为Flase a == b string str1 = "siki"; string str2 = "siki"; Console.WriteLine(str1.Equals(str2)); Student stu1 = new Student(18, "小芳"); Student stu2 = new Student(18, "小芳"); //默认方法值为Flase 重写Equals方法后值为True Console.WriteLine(stu1.Equals(stu2)); Console.WriteLine(stu1 == stu2); } } }

提示

  • 所有值类型、字符串比较就相当于a==b
  • 引用类型用Equals作比较时,比较的是引用地址,若需比较引用地址中的数据值,则需重写Equals方法

Student.cs

c#
using System; using System.Collections.Generic; using System.Text; namespace Equals判断相等 { class Student { private int age; private string name; public Student(int age, string name) { this.age = age; this.name = name; } public override bool Equals(object obj) //重写Equals方法 { Student stu = (Student)obj;//强制转换 if(age==stu.age && name==stu.name) { return true; } return false; } } }