- //值类型对象的数据存储在栈中,而引用对象的数据存储在堆区
- //值类型和引用类型的不同的存储方案对程序逻辑的影响却是必须透彻了解的
- using System;
- class TestValueRef
- {
- public int value;
- }
- class Test
- {
- public static void Main()
- {
- int valOne=0;
- int valTwo=valOne;
- int valThree=333;
- valTwo=333;//valOne==0 无影响
-
- TestValueRef Ref1=new TestValueRef();
- TestValueRef Ref2=Ref1;//栈中的Ref1和Ref2指向堆中同一个地方
- Ref2.value=444;//Ref1.value==444 有影响
-
- Console.WriteLine("{0},{1},{2}",valOne,valTwo,valThree);
- Console.WriteLine("{0},{1}",Ref1.value,Ref2.value);
- ///////////////////////////////////////////////////////
- //ReferenceEquals()判断引用是否相等,Equal()判断内容是否相等
- //测试值类型对象的“相等的含义”
- if(Object.ReferenceEquals(valOne,valTwo))//赋值是内容的赋值,引用是不可能相等的
- {
- Console.WriteLine("The references of valOne and valTwo are equal");
- }
- else
- {
- Console.WriteLine("The references of valOne and valTwo are not equal");
- }
-
- if(Object.ReferenceEquals(valTwo,valThree))//仅内容一样
- {
- Console.WriteLine("The references of valTwo and valThree are equal");
- }
- else
- {
- Console.WriteLine("The references of valTwo and valThree are not equal");
- }
-
- if(Object.Equals(valTwo,valThree))//Equals()内容一样就相等
- {
- Console.WriteLine("valTwo and valThree are equal");
- }
- else
- {
- Console.WriteLine("valTwo and valThree are not equal");
- }
- /////////////////////////////////////////////////////////////////
- //测试引用类型对象的“相等的含义”
- if(Object.ReferenceEquals(Ref1,Ref2))//赋值是引用,两个引用相等,则两个引用对象的数据存放在堆中的同一个位置
- {
- Console.WriteLine("The references of Ref1 and Ref2 are equal");
- }
- else
- {
- Console.WriteLine("The references of Ref1 and Ref2 are not equal");
- }
- if(Object.Equals(Ref1,Ref2))//两个引用相等,数据成员必然也相等
- {
- Console.WriteLine("Ref1 and Ref2 are equal");
- }
- else
- {
- Console.WriteLine("Ref1 and Ref2 are not equal");
- }
-
- TestValueRef Ref3=new TestValueRef();
- Ref3.value=444;
- if(Object.ReferenceEquals(Ref1,Ref3))//引用不同
- {
- Console.WriteLine("The references of Ref1 and Ref3 are equal");
- }
- else
- {
- Console.WriteLine("The references of Ref1 and Ref3 are not equal");
- }
-
- if(Object.Equals(Ref1,Ref3))//重点,类型相同,数据相等,引用不同是不“相等的”(可以理解为栈中存放的地址不同所致)
- {
- Console.WriteLine("Ref1 and Ref3 are equal");
- }
- else
- {
- Console.WriteLine("Ref1 and Ref3 are not equal");
- }
- }
- }
- /*
- 0,333,333
- 444,444
- The references of valOne and valTwo are not equal
- The references of valTwo and valThree are not equal
- valTwo and valThree are equal
- The references of Ref1 and Ref2 are equal
- Ref1 and Ref2 are equal
- The references of Ref1 and Ref3 are not equal
- Ref1 and Ref3 are not equal
- */
复制代码
|