gpt4 book ai didi

c# - C# 是否在声明非空字符串时隐式分配一个空字符串?

转载 作者:太空狗 更新时间:2023-10-30 00:59:39 24 4
gpt4 key购买 nike

我关心的是对可追溯到 2011 年的先前答案的评论:Immutable strings .

据说有这段代码

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

如您所见,这里没有使用空字符串。

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

关于c# - C# 是否在声明非空字符串时隐式分配一个空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54322788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com