有没有办法在 C# 中将插值字符串拆分为多行,同时在运行时执行相同的性能

Spa*_*man 3 c# string string-interpolation

我一直在与同事讨论格式化以下代码的最佳方法。

return $" this is a really long string.{a} this is a really long string. this is a really long string. this is a really long string. this is a really long string. this is a really long string. this is a really long string. this is a really long string. this is a really long string. this is a really long string. this is a really long string. this is a really long string.{b} this is a really long string. this is a really long string. this is a really long string. this is a really long string. this is a really long string. this is a really long string.{c}";
Run Code Online (Sandbox Code Playgroud)

我的转到是:(预先指定点上的换行符,即大约 80 个字符)

return  $" this is a really long string.{a} this is a really long string. this is a really long string." +
        $" this is a really long string. this is a really long string. this is a really long string." +
        $" this is a really long string. this is a really long string. this is a really long string." +
        $" this is a really long string. this is a really long string. this is a really long string." +
        $"{b} this is a really long string. this is a really long string. this is a really long string." +
        $" this is a really long string. this is a really long string. this is a really long string.{c}";
Run Code Online (Sandbox Code Playgroud)

但是我担心我在运行时添加了不必要的工作。是这样吗?如果是这样,有更好的方法吗?

另外我不认为换行是一个好的答案><

kon*_*ked 5

TLDR String.Format 正在被调用进行插值,因此连接正在插值的字符串意味着对 String.Format 的更多调用

我们看一下IL

当您遇到这些问题时,为了更好地了解实际发生的情况,最好查看 IL(中间语言),它是您的代码被编译成然后在 .NET 运行时上运行的语言。您可以使用ildasm检查已编译的 .NET DLL 和 EXE 的 IL。

连接多个字符串

因此,在这里您可以看到在幕后,正在为每个连接的字符串调用 String.Format。

连接字符串

使用一根长字符串

在这里您可以看到字符串格式仅被调用一次,这意味着如果您谈论性能,这种方式会稍微好一些。

一弦