gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:35:01 25 4
gpt4 key购买 nike

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

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/

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