Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当声明非空字符串时,C#是否隐式分配空字符串?_C#_String_Memory - Fatal编程技术网

当声明非空字符串时,C#是否隐式分配空字符串?

当声明非空字符串时,C#是否隐式分配空字符串?,c#,string,memory,C#,String,Memory,我关注的是对之前一个答案的评论,这个答案可以追溯到2011年: 有人声称这个代码 string str="a"; str +="b"; str +="c"; str +="d"; str +="e"; console.write(str) //output: abcde 在内存中创建10个字符串: "", "a", "b", "c", "d", "e", "ab", "abc", "abcd", and "abcde" 虽然我可以理解为什么会发生这种情况,但我仍然无法理解为什么首先会有一个

我关注的是对之前一个答案的评论,这个答案可以追溯到2011年:

有人声称这个代码

string str="a";
str +="b";
str +="c";
str +="d";
str +="e";

console.write(str) //output: abcde
在内存中创建10个字符串:

"", "a", "b", "c", "d", "e", "ab", "abc", "abcd", and "abcde"
虽然我可以理解为什么会发生这种情况,但我仍然无法理解为什么首先会有一个“”字符串。有人能给我一个提示吗?也许事实并非如此? C#文档并没有阐明这个问题。
我在这里唯一的猜测是C#的字符串是ref类型,所以默认情况下它是
null
,但就像……在这个例子中,它在一开始就得到一个值,所以我有点困惑

答案是:不,不是

如果您反编译为发布版本生成的代码,您将看到如下内容:

private static void Main()
{
    Console.WriteLine(string.Concat(string.Concat(string.Concat(string.Concat("a", "b"), "c"), "d"), "e"));
}
为该代码生成的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
正如您所看到的,这里没有空字符串的用途


(为了更好地支持调试器,生成的代码与调试版本略有不同,但它仍然不会创建空字符串。)

我看不出空字符串
会得到分配链接到实际答案的任何原因。在评论中,虽然没有解释,但事实上陈述了该主张:关于10字符串icluding
的假设在评论中,没有任何证据。我不知道这是否可以被视为是的,我很怀疑一个7岁的评论没有引用。基于这样的注释提出问题不是一个好主意。IMO.String.Empty是预定义的,可能出现在任何列出“内存中的字符串”的诊断工具中。此代码中不使用它。