【发布时间】:2012-01-20 11:54:46
【问题描述】:
为什么默认情况下只有文字字符串保存在实习池中?
来自MSDN的示例:
String s1 = "MyTest";
String s2 = new StringBuilder().Append("My").Append("Test").ToString();
String s3 = String.Intern(s2);
Console.WriteLine("s1 == '{0}'", s1);
Console.WriteLine("s2 == '{0}'", s2);
Console.WriteLine("s3 == '{0}'", s3);
Console.WriteLine("Is s2 the same reference as s1?: {0}", (Object)s2==(Object)s1);
Console.WriteLine("Is s3 the same reference as s1?: {0}", (Object)s3==(Object)s1);
/*
This example produces the following results:
s1 == 'MyTest'
s2 == 'MyTest'
s3 == 'MyTest'
Is s2 the same reference as s1?: False
Is s3 the same reference as s1?: True
*/
【问题讨论】:
-
为什么要对每个字符串进行实习?
-
@BoltClock,为什么要对每个文字字符串进行实习?
-
interned 的主要原因是为了节省内存空间,否则会因为在整个程序中多次重复相同的字符串而浪费,更不用说它很容易做到这一点。但我想不出非文字字符串被实习的理由。
标签: c# .net string compiler-construction clr