且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CLR字符串引用不匹配(始终)

更新时间:2023-02-21 15:38:17

此博客条目解释了原因。

在简而言之,如果您的字符串不是通过 ldstr 分配的(即,它不是在代码中定义的字符串文字),则它不会以

In short, if your string isn't allocated through ldstr (i.e. it's not a string literal defined within your code), it doesn't end up in the (hash) table of interned strings, and therefore interning doesn't occur.

解决方案是调用 String.Intern(str) 。 Intern方法使用实习生池来搜索等于 str 值的字符串。如果存在这样的字符串,则返回其在内部缓冲池中的引用。如果字符串不存在,则将对str的引用添加到内部缓冲池,然后返回该引用。

The solution is to call String.Intern(str). 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.

不要锁定在字符串上,尤其是当您尝试使用两个不同的参考变量来尝试指向同一(可能是)实习字符串时。

Don't lock on strings, especially if you're attempting to use two different reference variables to attempt to point to the same (possibly) interned string.

还请注意,对字符串进行内部处理有一些缺点。由于预计字符串文字在该程序的生存期内不会更改,因此在程序退出之前不会对垃圾回收的字符串进行垃圾回收。

Also note that there are some disadvantages to interning strings. Because string literals are not expected to change during the program's lifetime, interned strings are not garbage collected until your program exits.