Equals和==檢查引用是否相等。 但它的行爲不同,爲什麼? 這裏Equals vs ==的行爲不同
Console.WriteLine(c == d); //False
Console.WriteLine(c.Equals(d)); //True
Console.WriteLine(cc == dd); //True
Console.WriteLine(cc.Equals(dd));//True
有人可以解釋幕後發生的事情。
//https://blogs.msdn.microsoft.com/csharpfaq/2004/03/29/when-should-i-use-and-when-should-i-use-equals/
public void StringDoubleEqualsVsEquals()
{
// Create two equal but distinct strings
string a = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
string b = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
Console.WriteLine(a == b); //True
Console.WriteLine(a.Equals(b)); //True
// Now let's see what happens with the same tests but with variables of type object
object c = a;
object d = b;
Console.WriteLine(c == d); //False
Console.WriteLine(c.Equals(d)); //True
/*************************************************************************/
Console.WriteLine(Environment.NewLine);
string aa = "1";
string bb = "1";
Console.WriteLine(aa == bb);//True
Console.WriteLine(aa.Equals(bb));//True
object cc = aa;
object dd = bb;
Console.WriteLine(cc.GetType());//System.String
Console.WriteLine(dd.GetType());//System.String
Console.WriteLine(cc == dd);//True
Console.WriteLine(cc.Equals(dd));//True
Console.ReadKey();
}
字符串'=='運算符檢查值而不是引用https://msdn.microsoft.com/en-us/library/362314fe.aspx –
無論是'Equals'還是'=='都不能保證測試以供參考平等。 – Lee
[用於字符串的'=='可以進行值比較,而不是參考比較。](https://msdn.microsoft.com/en-us/library/system.string.op_equality(v = vs.110).aspx ) –