Object.ReferenceEquals方法原型
public static bool ReferenceEquals(
object objA,
object objB
)
namespace TestReferenceEquality { struct TestStruct { public int Num { get; private set; } public string Name { get; private set; } public TestStruct(int i, string s) : this() { Num = i; Name = s; } } class TestClass { public int Num { get; set; } public string Name { get; set; } } class Program { static void Main() { //测试对象相等性 #region ReferenceTypes // 创建具有两个相同值的引用实例。
TestClass tcA = new TestClass() { Num = 1, Name = "New TestClass" }; TestClass tcB = new TestClass() { Num = 1, Name = "New TestClass" }; Console.WriteLine("ReferenceEquals(tcA, tcB) = {0}", Object.ReferenceEquals(tcA, tcB)); // false // 赋值后, 引用同一对象
tcB = tcA; Console.WriteLine("After asignment: ReferenceEquals(tcA, tcB) = {0}", Object.ReferenceEquals(tcA, tcB)); // true #endregion // 演示两个值类型实例从不具有引用相等性。
#region ValueTypes TestStruct tsC = new TestStruct( 1, "TestStruct 1");
//虽是拷贝,具有相同的值,但却不是同一对象,涉及装箱
TestStruct tsD = tsC; Console.WriteLine("After asignment: ReferenceEquals(tsC, tsD) = {0}", Object.ReferenceEquals(tsC, tsD)); // false #endregion #region stringRefEquality //"Hello world!";常量字符串在内存中只有一份,所以两者指向同一内存
string strA = "Hello world!"; string strB = "Hello world!"; Console.WriteLine("ReferenceEquals(strA, strB) = {0}", Object.ReferenceEquals(strA, strB)); // true // 改变引用用后,两者不再相等 strA = "Goodbye world!"; Console.WriteLine("strA = \"{0}\" strB = \"{1}\"", strA, strB); Console.WriteLine("After strA changes, ReferenceEquals(strA, strB) = {0}", Object.ReferenceEquals(strA, strB)); // false //string对象在运行期间被创建,跟strB是完全不同的两个对象,在用 Object.ReferenceEquals判断引用相等时则返回false
StringBuilder sb = new StringBuilder("Hello world!"); string stringC = sb.ToString(); // False: Console.WriteLine("ReferenceEquals(stringC, strB) = {0}", Object.ReferenceEquals(stringC, strB)); // 字符串类重载了==运算符来执行相等比较
Console.WriteLine("stringC == strB = {0}", stringC == strB); // true #endregion } } }
对于值类型的采用ReferenceEquals将返回false,引用类型采用ReferenceEquals比较时,若是引用同一实例则返回true,
判断字符串内容是否相等可直接利用字符串类的重载运算符==来判断
为了最大程度地减小出现错误的可能性,最好在必须确定两个对象是否具有引用相等性时使用 ReferenceEquals。