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

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


我的定位是:(在指定点上换行,即大约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#中的多行,同时在运行时在性能上执行相同的操作-LMLPHP

使用一个长字符串

在这里,您看到String格式仅被调用一次,这意味着如果您在谈论性能,则这种方法会稍微好一点。

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

09-26 11:50