C#中 == 与 Equals的简单理解

时间:2023-03-09 04:06:06
C#中 == 与 Equals的简单理解
 using System;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Security.Cryptography;
using System.Text; namespace myMethod
{
class Person
{
public int age = ;
public string name = ""; //在程序的生命周期中,相同的对象、变量返回的HashCode是 相同且唯一的。
//但是绝对不允许做持久性存储,程序一旦结束并重新启动后,同样的对象无法获得上次程序运行时的HashCode。
//如果要把引用类型做为Dictionary或HashTable的key使用时,必须重写这两个方法。
#region public override bool Equals(object obj)
{
Person p = obj as Person; if (this.age == p.age && this.name == p.name)
return true; return false;
} //即使是不同的实例,如果对象的名字是一样的,这样取得的 GetHashCode() 也是相等的。重写GetHashCode()其实是比较困难的
public override int GetHashCode()
{
return name.GetHashCode();
} #endregion
} class lgs
{
static void Main()
{
//Equals(自定义类需要重写Equals)比较的永远是变量的内容是否相同,而 == 比较的则是引用地址是否相同 int a = ;
int b = ;
Console.WriteLine(a == b); //true
Console.WriteLine(a.Equals(b)); //true string str1 = "abc";
string str2 = "abc";
Console.WriteLine(str1 == str2); //true
Console.WriteLine(str1.Equals(str2)); //true Person p1 = new Person();
p1.age = ; p1.name = "";
Person p2 = new Person();
p2.age = ; p2.name = "";
Console.WriteLine(p1 == p2);
Console.WriteLine(p1.Equals(p2)); Console.WriteLine(p1.GetHashCode());
Console.WriteLine(p2.GetHashCode()); Console.ReadKey();
}
}
}

关于 GetHashCode 方法,这里有两篇不错的文章:

https://blog.****.net/cnhk1225/article/details/23391885

https://www.cnblogs.com/xiaochen-vip8/p/5506478.html