该代码非常不言自明。我预计当我创建a1
并且b1
我正在创建两个包含相同文本的不同字符串实例时。所以我a1 == b1
认为这是真的,但object.ReferenceEquals(a1,b1)
会是假的,但事实并非如此。为什么?
//make two seemingly different string instances
string a1 = "test";
string b1 = "test";
Console.WriteLine(object.ReferenceEquals(a1, b1)); // prints True. why?
//explicitly "recreating" b2
string a2 = "test";
string b2 = "tes";
b2 += "t";
Console.WriteLine(object.ReferenceEquals(a2, b2)); // prints False
//explicitly using new string constructor
string a3 = new string("test".ToCharArray());
string b3 = new string("test".ToCharArray());
Console.WriteLine(object.ReferenceEquals(a3, b3)); // prints False