我一直在与同事讨论格式化以下代码的最佳方式。
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}";
我的 goto 是:(在预先指定的点换行,即大约 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}";
但是我担心我在运行时添加了不必要的工作。是这样吗? 如果是这样,是否有更好的方法?
另外我觉得换行不是一个好的答案><
最佳答案
TLDR String.Format 被调用用于插值,因此连接被插值的字符串意味着对 String.Format 的更多调用
让我们看看IL
当您有这些问题时,要更好地了解实际发生了什么,最好查看 IL(中间语言),它是您的代码被编译成然后在 .NET 运行时上运行的语言。您可以使用 ildasm用于检查已编译的 .NET DLL 和 EXE 的 IL。
连接多个字符串
所以在这里您可以看到在幕后,正在为每个连接的字符串调用 String.Format。
使用一个长字符串
在这里您看到字符串格式只被调用一次,这意味着如果您以这种方式谈论性能会稍微好一些。
关于c# - 有没有一种方法可以在 C# 中将内插字符串拆分为多行,同时在性能方面在运行时执行相同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38470252/