前言
string是一种很特殊的数据类型,它既是基元类型又是引用类型,在编译以及运行时,.Net都对它做了一些优化工作,正式这些优化工作有时会迷惑编程人员,使string看起来难以琢磨。本文将给大家详细介绍关于C#字符串优化String.Intern、IsInterned的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
首先看一段程序:
using System;
class Program
{
static void Main(string[] args)
{
string a = "hello world";
string b = a;
a = "hello";
Console.WriteLine("{0}, {1}", a, b);
Console.WriteLine(a == b);
Console.WriteLine(object.ReferenceEquals(a, b));
}
}
这个没有什么特殊的地方,相信大家都知道运行结果:
hello, hello world
False
False
第二个WriteLine使用==比较两个字符串,返回False是因为他们不一致。而最后一个WriteLine返回False,因为a、b的引用不一致。
接下来,我们在代码的最后添加代码:
Console.WriteLine((a + " world") == b);
Console.WriteLine(object.ReferenceEquals((a + " world"), b));
这个的输出,相信也不会出乎大家的意料。前者返回True,因为==两边的内容相等;后者为False,因为+运算符执行完毕后,会创建一个新的string实例,这个实例与b的引用不一致。
上面这些就是对象的通常工作方式,两个独立的对象可以拥有同样的内容,但他们却是不同的个体。
接下来,我们就来说一下string不寻常的地方
看一下下面这段代码:
using System;
class Program
{
static void Main(string[] args)
{
string hello = "hello";
string helloWorld = "hello world";
string helloWorld2 = hello + " world";
Console.WriteLine("{0}, {1}: {2}, {3}", helloWorld, helloWorld2,
helloWorld == helloWorld2,
object.ReferenceEquals(helloWorld, helloWorld2));
}
}
运行一下,结果为:
hello world, hello world: True, False
再一次,没什么意外,==返回true因为他们内容相同,ReferenceEquals返回False因为他们是不同的引用。
现在在后面添加这样的代码:
helloWorld2 = "hello world";
Console.WriteLine("{0}, {1}: {2}, {3}", helloWorld, helloWorld2,
helloWorld == helloWorld2,
object.ReferenceEquals(helloWorld, helloWorld2));
运行,结果为:
hello world, hello world: True, True
等一下,这里的hellowWorld与helloWorld2引用一致?这个结果,相信很多人都有些接受不了。这里的helloWorld2与上面的hello + " world"应该是一样的,但为什么ReferenceEquals返回的是True?










