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);
}
}
}
提示
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;
}
}
}