CLR字符串引用不匹配(始终) [英] CLR String References Don't (Always) Match

查看:87
本文介绍了CLR字符串引用不匹配(始终)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自Richter和此讨论,我希望任何两个相同的字符串都是相同的引用。但是就在LINQPad中,我在这个话题上得到了不同的结果。代码如下:

From Richter and this discussion, I would expect any two "identical" strings to be the same reference. But just now in LINQPad I got mixed results on this topic. Here is the code:

void Main()
{
    string alpha = String.Format("Hello{0}", 5);
    string brava = String.Format("Hello{0}", 5);
    ReferenceEquals(alpha, brava).Dump();
    String.IsInterned(alpha).Dump();
    String.IsInterned(brava).Dump();

    alpha = "hello";
    brava = "hello";
    ReferenceEquals(alpha, brava).Dump();
}

这是Dump()调用的结果:

And here are the results from the Dump() calls:

False
Hello5
Hello5
True

我希望第一个和最后一个 ReferenceEquals 都为 True

I would have expected both the first and last ReferenceEquals to be True. What happened?

除了上面的示例,在什么其他情况下ReferenceEquals还会失败?例如,多线程?

Besides the example above, in what other cases would the ReferenceEquals fail? For example, multi-threading?

例如,如果我使用传递到方法中的字符串参数作为对其进行锁定的对象,则此问题很重要。 。在这种情况下,引用最好是相同的!!

This issue is important if, for example, I'm using string parameters passed into a method as the object upon which a lock is taken. The references better be the same in that case!!!

推荐答案

此博客条目解释了原因。

在简而言之,如果您的字符串不是通过 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.

这篇关于CLR字符串引用不匹配(始终)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆