给定:
object literal1 = "abc";
object literal2 = "abc";
object copiedVariable = string.Copy((string)literal1);
if (literal1 == literal2)
Console.WriteLine("objects are equal because of interning");//Are equal
if(literal1 == copiedVariable)
Console.WriteLine("copy is equal");
else
Console.WriteLine("copy not eq");//NOT equal
这些结果表明 copiedVariable
不受字符串驻留的影响。为什么?
在某些情况下,具有未驻留的等效字符串是否有用,或者这种行为是由于某些语言细节引起的吗?
最佳答案
如果您考虑一下,字符串的驻留是它在编译时对文字触发的过程。这意味着:
- 当您将文字分配/绑定(bind)到变量时,它是隐式的
- 当你复制一个引用时它是隐含的(即字符串 a = some_other_string_variable;)
另一方面,如果您手动创建字符串的实例 - 在运行时使用 StringBuilder 或通过复制,那么您必须专门请求通过调用 Intern String 类的方法。
即使在文档的备注部分中也指出:
The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system. For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.
以及 Copy 的文档String 类的方法声明它:
Creates a new instance of String with the same value as a specified String.
这意味着它不会只返回对同一字符串的引用(来自实习生池)。再说一次,如果确实如此,那么它就没有多大用处了,不是吗?!
关于c# - 为什么实习生对字符串的副本不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15161225/