Re: 关于string的一个问题

 我前天(是前天吧?应该是吧)写了一篇文章 “关于string的一个问题 ”。 OC Life 同学给我提了很好的建议。我研究了一下 Andytao的 “ [你必须知道的.NET]第二十二回:字符串驻留(上)---带着问题思考”。 感觉之前的那篇文章可以忽略不计了。哎~~~自己怎么这么笨呢。

查MSDN,发现有这么一段话(其实Andytao的文章里也有,只不过我先看到MSDN,后来在看到了他的话,嘿嘿)
“The common language runtime automatically maintains a table, called the "intern pool", which contains a single instance of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically.

The intern pool conserves string storage. If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.”

就是说,在内存中,CLR维护一个驻留池,将字符串存放到里面。当给一个变量分配字符串的时候,CLR先到驻留池里找,如果找到了,就将该字符串的引用给这个变量,如果没有,就将该字符串创建到驻留池里,然后在将引用给该变量。 这就是为什么string s1 = "abc"; string s2 = "abc"; s1的指针=s2的指针了。


创建的时候,应该是在compile时创建的。 所以动态创建的字符串在第一次使用时,调用string.IsIntern这个方法时,得到的是空。 比如

string s1 = "ab"; s1+= "c" ;

string.IsIntern(s1) 是=空的。


但是如果

string s1 = "ab"; s1+= "c" ;string s2 = "abc";

则string.IsIntern(s1)  就= "abc"了。因为,在编译的时候 “string s2 = "abc";” 被CLR写进intern pool了。


再次感谢oc life!



posted @ 2009-10-14 09:52  麦穗  阅读(299)  评论(0编辑  收藏  举报