为什么某些相同的字符串未嵌入.NET? [英] Why some identical strings are not interned in .NET?

查看:81
本文介绍了为什么某些相同的字符串未嵌入.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string s1 = "test";
string s5 = s1.Substring(0, 3)+"t"; 
string s6 = s1.Substring(0,4)+"";   
Console.WriteLine("{0} ", object.ReferenceEquals(s1, s5)); //False
Console.WriteLine("{0} ", object.ReferenceEquals(s1, s6)); //True

字符串s5和s6的值均与s1(测试)相同。基于字符串插入概念,两个语句必须都评估为true。有人可以解释为什么s5与s1没有相同的引用吗?

Both the strings s5 and s6 have same value as s1 ("test"). Based on string interning concept, both the statements must have evaluated to true. Can someone please explain why s5 didn't have the same reference as s1?

推荐答案

您应该得到对于不是字符串文字的 string 对象上的 ReferenceEquals 的调用为false

You should get false for calls of ReferenceEquals on string objects that are not string literals.

本质上,最后一行巧合地显示 True :发生的情况是,当您传递空字符串进行字符串连接时,库优化可以识别出这一点,并返回原始字符串。这与实习无关,因为您以任何其他方式从控制台或构造读取的字符串也会发生相同的事情:

Essentially, the last line prints True by coincidence: what happens is that when you pass an empty string for string concatenation, library optimization recognizes this, and returns the original string. This has nothing to do with interning, as the same thing will happen with strings that you read from console or construct in any other way:

var s1 = Console.ReadLine();
var s2 = s1+"";
var s3 = ""+s1;
Console.WriteLine(
    "{0} {1} {2}"
,   object.ReferenceEquals(s1, s2)
,   object.ReferenceEquals(s1, s3)
,   object.ReferenceEquals(s2, s3)
);

上面的照片

True True True

演示。

这篇关于为什么某些相同的字符串未嵌入.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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