您的位置:首页 > 职场人生

equals与==的区别

2009-12-06 00:04 169 查看
对于值类型,如果对象的值相等,则相等运算符(==)返回true,否则返回false。对于string以外的引用类型,如果两个对象引用同一个对象,则==返回true。对于string类型,==比较字符串的值。
==操作比较的是两个变量的值是否相等。
equals()方法比较的是两个对象的内容是否一致.equals也就是比较引用类型是否是对同一个对象的引用。
今天拜读anytao的大作时对string类有了新的认识,那就是string类型驻留即string.IsInterned这个方法,在vs中是这么定义的:

//Summary:


//RetrievesareferencetoaspecifiedSystem.String.


//


//Parameters:


//str:


//ASystem.String.


//


//Returns:


//ASystem.Stringreferencetostrifitisinthecommonlanguageruntime


//"internpool";otherwisenull.


//


//Exceptions:


//System.ArgumentNullException:


//strisnull.


publicstaticstringIsInterned(stringstr);在MSDN中解释如下:如果str位于公共语言运行时"暂存池"中,则为对它的String引用;否则为null引用
公共语言运行时会自动维护一个名为"暂存池"的表,它包含在程序中声明的每个唯一字符串常数的单个实例,以及以编程方式添加的String的任何唯一实例。暂存池可以节约字符串存储区。如果将字符串常数分配给几个变量,则每个变量设置为引用暂存池中的同一常数,而不是引用具有相同值的String的几个不同实例。此方法在暂存池中查找str。如果已经将str放入暂存池中,则返回对此实例的引用;否则返回null引用(在VisualBasic中为Nothing)。将此方法与Intern方法进行比较。此方法不返回布尔值,但仍可以在需要布尔值的地方使用。
但该说明解释的并不十分清楚,大家可以通过下面的例子得到更多的信息:
//Release:code09,2008/08/25
//Author:Anytao,
'target='_blank'>http://www.anytao.com
staticvoidMain()
{
strings1="abc";
strings2="ab";
strings3=s2+"c";
Console.WriteLine(ReferenceEquals(s1,s3));
}
//Release:code07,2008/08/20
//Author:Anytao,
'target='_blank'>http://www.anytao.com
publicconststrings1="abc";
staticvoidMain()
{
strings2="ab";
s2+="c";
Console.WriteLine(string.IsInterned(s2)??"null");
}
//Release:code06,2008/08/20
//Author:Anytao,
'target='_blank'>http://www.anytao.com
staticvoidMain()
{
strings2="ab";
s2+="c";
Console.WriteLine(string.IsInterned(s2)??"null");
strings1=GetStr();
}
privatestaticstringGetStr()
{
return"abc";
}
//Release:code08,2008/08/20
//Author:Anytao,
'target='_blank'>http://www.anytao.com
publicstaticstrings1="abc";
staticvoidMain()
{
strings2="ab";
s2+="c";
Console.WriteLine(string.IsInterned(s2)??"null");
}
以上代码转载自http://www.cnblogs.com/anytao/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  职场 休闲