字符串实习?

编程入门 行业动态 更新时间:2024-10-26 13:19:19
本文介绍了字符串实习?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

第二个ReferenceEquals调用返回false。为什么不对s4中的字符串进行实习? (我不在乎StringBuilder相对于字符串连接的优势。)

The second ReferenceEquals call returns false. Why isn't the string in s4 interned? (I don't care about the advantages of StringBuilder over string concatenation.)

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); ,我仍然是假的。

When I do String.Intern(s4);, I still get false.

在这里,s3和s4都被拘留了,但是它们的引用不相等?

Here, both s3 and s4 are interned but their references are not equal?

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 被拘留。但是,当您执行 s4 + = m; 时,您创建了一个不会被插入的新字符串,因为它的值不是字符串文字,而是a的结果字符串串联操作。结果, s3 和 s4 是在两个不同的内存位置中的两个不同的字符串实例。

The string in s4 is interned. However, when you execute s4 += "m";, you have created a new string that will not be interned as its value is not a string literal but the result of a string concatenation operation. As a result, s3 and s4 are two different string instances in two different memory locations.

有关字符串实习的更多信息,请参见此处,特别是在最后一个示例中。当您执行 String.Intern(s4)时,您确实在对字符串进行了内部检查,但是您仍未在这两个被内部检查的字符串之间执行引用相等性测试。 String.Intern 方法返回被插入的字符串,因此您需要执行以下操作:

For more information on string interning, look here, specifically at the last example. When you do String.Intern(s4), you are indeed interning the string, but you are still not performing a reference equality test between those two interned strings. The String.Intern method returns the interned string, so you would need to do this:

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 s5 = String.Intern(s4); Console.Write(object.ReferenceEquals(s3, s5)); //true

更多推荐

字符串实习?

本文发布于:2023-11-13 09:23:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583998.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!