string s1 = "tom";
string s2 = "tom";
Console.Write(object.ReferenceEquals(s2, s1)); //true
string s3 = "tom";
string s4 = "to";
s4 += "m";
Console.Write(object.ReferenceEquals(s3, s4)); //false
当我执行
String.Intern(s4);
时,仍然返回false。在这里,s3和s4都被interned,但它们的引用不相等?
string s3 = "tom";
string s4 = "to";
s4 += "m";
String.Intern(s4);
Console.WriteLine(s3 == s4); //true
Console.WriteLine(object.ReferenceEquals(s3, s4)); //false
Console.WriteLine(string.IsInterned(s3) != null); //true (s3 is interned)
Console.WriteLine(string.IsInterned(s4) != null); //true (s4 is interned)
Intern 方法使用内部池来搜索与 str 值相等的字符串。如果存在这样的字符串,则返回其在内部池中的引用。如果该字符串不存在,则将对 str 的引用添加到内部池中,然后返回该引用。
- Scott Dorman