首先看几个例子:
示例1:
static void Main()
{
string s2 = "ab";
s2 += "c";
Console.WriteLine(string.IsInterned(s2) ?? "null");
string s1 = "abc";
}
示例2:
static void Main()
{
string s2 = "ab";
s2 += "c";
Console.WriteLine(string.IsInterned(s2) ?? "null");
string s1 = GetStr(); // 这个方法返回字符串“abc”
}
示例3:
public const string s1 = "abc";
static void Main()
{
string s2 = "ab";
s2 += "c";
Console.WriteLine(string.IsInterned(s2) ?? "null");
}
示例4:public static string s1 = "abc";static void Main(){string s2 = "ab";s2 += "c";
Console.WriteLine(string.IsInterned(s2) ?? "null");}
示例1的运行结果:"abc"
示例2的运行结果:null
示例3的运行结果:null
示例4的运行结果:"abc"
我对示例1的结果非常疑惑,什么时机才改变intern pool 的hashtable?按代码执行的先后顺序来讲,"abc"应该是没有被驻留才对,但结果刚好相反。
另外,对示例3、4. 是否说明const string s1="abc" 不会触发字符串驻留池的改变,static string s1 = "abc" 才会引起。这两种情况下的string在内存中的存储位置是否有区别?