static void Main(string[] args)
{
string s1 = "test";
string s2 = "test";
Console.WriteLine(s1 == s2);//true
Console.WriteLine(s1.Equals(s2));//true
object o1 = s1;
object o2 = s2;
Console.WriteLine(o1 == o2);//true
Console.WriteLine(o1.Equals(o2));//true
string s3 = new string(new char[] { 't', 'e', 's', 't' });
string s4 = new string(new char[] { 't', 'e', 's', 't' });
Console.WriteLine(s3 == s4);//true
Console.WriteLine(s3.Equals(s4));//true
object o3 = s3;
object o4 = s4;
Console.WriteLine(o3 == o4);//false
Console.WriteLine(o3.Equals(o4));//true
Class1 c1 = new Class1("a");
Class1 c2 = new Class1("a");
Console.WriteLine(c1 == c2);//false
Console.WriteLine(c1.Equals(c2));//false
Class1 c3 = new Class1("a");
Class1 c4 = c3;
Console.WriteLine(c3 == c4);//true
分析:因为值类型存储在内存中的栈中,引用类型的变量在栈中只存储引用类型变量的地址,而其本身则存储在堆中
“==”比较两个变量的值是否相等,对于两个引用变量表示两个变量的地址是否相同,即栈中的内容是否相同
{
string s1 = "test";
string s2 = "test";
Console.WriteLine(s1 == s2);//true
Console.WriteLine(s1.Equals(s2));//true
object o1 = s1;
object o2 = s2;
Console.WriteLine(o1 == o2);//true
Console.WriteLine(o1.Equals(o2));//true
string s3 = new string(new char[] { 't', 'e', 's', 't' });
string s4 = new string(new char[] { 't', 'e', 's', 't' });
Console.WriteLine(s3 == s4);//true
Console.WriteLine(s3.Equals(s4));//true
object o3 = s3;
object o4 = s4;
Console.WriteLine(o3 == o4);//false
Console.WriteLine(o3.Equals(o4));//true
Class1 c1 = new Class1("a");
Class1 c2 = new Class1("a");
Console.WriteLine(c1 == c2);//false
Console.WriteLine(c1.Equals(c2));//false
Class1 c3 = new Class1("a");
Class1 c4 = c3;
Console.WriteLine(c3 == c4);//true
Console.WriteLine(c3.Equals(c4));//true
class Class1
{
string a;
public Class1(string a)
{
this.a = a;
}
}
分析:因为值类型存储在内存中的栈中,引用类型的变量在栈中只存储引用类型变量的地址,而其本身则存储在堆中
“==”比较两个变量的值是否相等,对于两个引用变量表示两个变量的地址是否相同,即栈中的内容是否相同
“equals”表示两个变量是否是对同一个对象的引用,即堆中内容是否相同
字符串是一特殊的引用类型,
s3与s4两个字符串的内容相等,o3与o4是内存中两个不同对象但内容相同则其地址不同则有o3==o4为False,o3与o4的内容相同则o3.equals(o4)为true
o1与o2是内容相等的,地址也是相等的,因为系统没有给s2分配内存,只是将“test”指向s2,所以s1和s2 direct to a same address.
p1 and p2 are different object in the memory, So the addresses of both are different,
p3 and p4......