我们正在创建Employee类的两个实例e和e1。e分配给e1。这两个对象都指向同一个参考,因此对于所有Equals,我们将得到预期的输出。
在第二种情况下,即使属性值相同,我们也可以观察到。等于返回false。本质上,当参数引用不同的对象时。等于不检查值,并且始终返回false。
class Program{ static void Main(string[] args){ Employee e = new Employee(); e.Name = "Test"; e.Age = 27; Employee e2 = new Employee(); e2 = e; var valueEqual = e.Equals(e2); Console.WriteLine(valueEqual); //第二种情况 Employee e1 = new Employee(); e1.Name = "Test"; e1.Age = 27; var valueEqual1 = e.Equals(e1); Console.WriteLine(valueEqual1); Console.ReadLine(); } } class Employee{ public int Age { get; set; } public string Name { get; set; } }
输出结果
True False
class Program{ static void Main(string[] args){ Employee e = new Employee(); e.Name = "Test"; e.Age = 27; Employee e2 = new Employee(); e2 = e; var valueEqual = e.Equals(e2); Console.WriteLine(valueEqual); Employee e1 = new Employee(); e1.Name = "Test"; e1.Age = 27; var valueEqual1 = e.Equals(e1); Console.WriteLine(valueEqual1); Console.ReadLine(); } } class Employee{ public int Age { get; set; } public string Name { get; set; } public override bool Equals(object? obj){ if (obj == null) return false; if (this.GetType() != obj.GetType()) return false; Employee p = (Employee)obj; return (this.Age == p.Age) && (this.Name == p.Name); } public override int GetHashCode(){ return Age.GetHashCode() ^ Name.GetHashCode(); } }
输出结果
True True