代码改变世界

比较两个引用的几种方法

2010-09-07 10:30  zlty  阅读(315)  评论(0编辑  收藏  举报

昨天面试被问到,自己整理了一下.不知道是否正确.

 

string strA = "aaa";
string strA_cp = strA;
string strB = "bbb";
string strC = "bbb";
int a = strA.CompareTo(strA_cp);//0
a = strA.CompareTo(strB);//-1
a = strB.CompareTo(strC);//0


bool b = Object.Equals(strA, strA_cp);//true
b = Object.Equals(strA, strB);//false
b = Object.Equals(strB, strC);//true

a
= strA.GetHashCode();//-625742108
a = strA_cp.GetHashCode();//-625742108
a = strB.GetHashCode();//2103075710
a = strC.GetHashCode();//2103075710

List
<string> lstStr = new List<string>() { strA, strC };
b
= lstStr.Contains(strA_cp);//true
b = lstStr.Contains(strB);//true

b
= ((object)strA == (object)strA_cp);//true
b = ((object)strA == (object)strB);//false
b = ((object)strC == (object)strB);//true

strC
= "ddd";
a
= strC.GetHashCode();//-1029223246

感觉不管哪种比较方式,最后都是使用object来比较.