C#中ReferenceEquals和Equals的区别

ReferenceEquals()判断两个字符串是否指向相同的内存地址;(判断引用)

Equals,先判断两个字符串有相同的内存位置,是则两个字符串相等;否则逐字符比较两个字符串,判断是否相等(先判断引用,在判断值是否相等)

下面举一个例子看一下:

 view plaincopy to clipboardprint?
string peom1 = "Kubla Khan";  
           string peom2 = "Kubla Khan";  
           string peom3 = String.Copy(peom2);  
           string peom4 = "kubla khan";  
 
           //ReferenceEquals()判断两个字符串是否指向相同的内存地址  
           Console.WriteLine("peom1 == peom2:"+(peom1 == peom2));//True  
           Console.WriteLine("peom1 == peom3:" + (peom1 == peom3));//True  
           Console.WriteLine("ReferenceEquals(peom1,peom3):" + ReferenceEquals(peom1, peom3));//False  
             
           //Equals,先判断两个字符串有相同的内存位置,则两个字符串相等;否则逐字符比较两个字符串,判断是否相等  
           Console.WriteLine("Equal(peom1,peom3):" +String.Equals(peom1, peom2));//true  
           Console.WriteLine("Equal(peom1,peom3):" + String.Equals(peom1, peom3));//true 

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/licl19870605/archive/2009/10/15/4676881.aspx

posted @ 2014-06-26 09:32  Coding_Yong  阅读(527)  评论(0编辑  收藏  举报