【发布时间】:2011-02-11 23:48:24
【问题描述】:
第二个 ReferenceEquals 调用返回 false。为什么 s4 中的字符串没有被实习? (我不关心 StringBuilder 相对于字符串连接的优势。)
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); 时,我仍然是假的。
这里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)
【问题讨论】:
-
请再次验证 s4 = String.Intern (s4); Console.Write (object.ReferenceEquals (s3, s4));对于 .NET 2.0、3.0、3.5、4.0,它返回 true。此外,如果您测试 s3 = String.Intern (s3); Console.Write (object.ReferenceEquals (s3, s1));你可以看到 s3 = String.Intern (s3);什么也不做,因为就像 Scott Dorman 所写的那样,从 s1 到 s3 的所有内容都已经被埋葬了,只有 s4 指向一个唯一的堆指针,然后我们用 s4 = String.Intern (s4);
-
string.Interned() 并不意味着传入的字符串对象是作为实习字符串创建的,这意味着在实习存储中存在一个具有相同值的对象。令人困惑,嗯!
-
有道理。但是 String.Intern(s4) 那么不实习字符串呢?
-
是的,它确实对字符串进行了实习,但您仍然没有比较实习参考。查看我的答案的更新以获取更多信息。来自 MSDN:
The Intern method uses the intern pool to search for a string equal to the value of str. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to str is added to the intern pool, then that reference is returned.
标签: c# string reference clr string-interning