我关注的是对可追溯到2011年的前一个答案的评论:不可变的字符串.
它声称有这个代码
string str="a";
str +="b";
str +="c";
str +="d";
str +="e";
console.write(str) //output: abcde
Run Code Online (Sandbox Code Playgroud)
在内存中创建10个字符串:
"", "a", "b", "c", "d", "e", "ab", "abc", "abcd", and "abcde"
Run Code Online (Sandbox Code Playgroud)
虽然我可以理解为什么会发生这种情况,但我仍然无法理解为什么首先会有一个""字符串.有人可以暗示我吗?也许情况甚至不是这样的?C#文档没有说明问题.我唯一的猜测是C#的字符串是一个ref类型,所以它null默认情况下,但是...在这个例子中它在一开始就得到一个值,所以我有点困惑.
答案是:不,它没有.
如果您反编译为发布版本生成的代码,您将看到如下内容:
private static void Main()
{
Console.WriteLine(string.Concat(string.Concat(string.Concat(string.Concat("a", "b"), "c"), "d"), "e"));
}
Run Code Online (Sandbox Code Playgroud)
为此代码生成的IL是:
IL_0000: ldstr "a"
IL_0005: ldstr "b"
IL_000a: call string [mscorlib]System.String::Concat(string, string)
IL_000f: ldstr "c"
IL_0014: call string [mscorlib]System.String::Concat(string, string)
IL_0019: ldstr "d"
IL_001e: call string [mscorlib]System.String::Concat(string, string)
IL_0023: ldstr "e"
IL_0028: call string [mscorlib]System.String::Concat(string, string)
IL_002d: call void [mscorlib]System.Console::WriteLine(string)
IL_0032: ret
Run Code Online (Sandbox Code Playgroud)
如您所见,那里没有使用空字符串.
(生成的代码对于调试版本略有不同,以便更好地支持调试器,但它仍然不会创建空字符串.)
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |