const String one = "1";
const String two = "2";
const String result = one + two + "34";
或作为 字面意思,如在最初的问题:
String result = "1" + "2" + "3" + "4";
然后编译器就会优化掉这些 +符号,这相当于:
const String result = "1234";
Furthermore, the compiler will remove extraneous constant expressions, and only emit them if they are used or exposed. For instance, this program:
const String one = "1";
const String two = "1";
const String result = one + two + "34";
public static void main(string[] args) {
Console.Out.WriteLine(result);
}
只生成一个字符串-常量 result(等于“1234”)。one和 two在产生的 IL 中不显示。
请记住,在运行时可能会有进一步的优化。
最后,关于实习,常量和文字是实习的,但是实习的值是在 IL 中生成的常量值,而不是文字。这意味着您可能得到比预期更少的字符串对象,因为多个相同定义的常量或文字实际上是同一个对象!以下事例说明了这一点:
public class Program
{
private const String one = "1";
private const String two = "2";
private const String RESULT = one + two + "34";
static String MakeIt()
{
return "1" + "2" + "3" + "4";
}
static void Main(string[] args)
{
string result = "1" + "2" + "34";
// Prints "True"
Console.Out.WriteLine(Object.ReferenceEquals(result, MakeIt()));
// Prints "True" also
Console.Out.WriteLine(Object.ReferenceEquals(result, RESULT));
Console.ReadKey();
}
}
public class Program
{
static void Main(string[] args)
{
string result = "";
for (int i = 0; i < 10; i++)
result += "a";
Console.ReadKey();
}
}
But (also surprisingly), multiple consecutive concatenations are combined by the compiler into a single multi-string concatenation. For example, this program also only produces 12 string instances! This is because "即使在一个语句中使用多个 + 运算符,字符串内容也只复制一次。"
public class Program
{
static void Main(string[] args)
{
string result = "";
for (int i = 0; i < 10; i++)
result += "a" + result;
Console.ReadKey();
}
}