c# - 有没有一种方法可以在 C# 中将内插字符串拆分为多行,同时在性能方面在运行时执行相同的操作

标签 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}";

我的 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。

Concatenated strings

使用一个长字符串

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

One string

关于c# - 有没有一种方法可以在 C# 中将内插字符串拆分为多行,同时在性能方面在运行时执行相同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38470252/

相关文章:

java - 使用正则表达式将字符串拆分为 3 部分

c - 未定义对gets_s的引用

javascript - 尝试选择 ul 的所选 li 元素的前一个 li 元素

bash 脚本 - 在 cat 中使用和扩展变量

c# - 字符串插值有什么意义?

c# - 如何: Select Distinct objects<T> from multiple Lists<T> with 1 or more properties of same type

c# - 请求的性能计数器不是自定义计数器,必须将其初始化为 ReadOnly。"on RouteTable.Routes.MapHubs();

c# - 我什么时候应该使用 "var"而不是 "object"?

c# - 在 ASP.NET C# Web 应用程序中动态创建图像的正确方法?

c++ - constexpr 构造函数不被称为隐式类型转换的 constexpr