C# 在C语言中,有没有一种方法可以在多行上分割插值字符串,同时在运行时根据性能执行相同的操作
我一直在与同事讨论格式化以下代码的最佳方法C# 在C语言中,有没有一种方法可以在多行上分割插值字符串,同时在运行时根据性能执行相同的操作,c#,string,string-interpolation,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
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运行时上运行。您可以使用检查编译的.NET DLL和EXE的IL
连接多个字符串
在这里您可以看到,在幕后,正在为每个连接的字符串调用String.Format
使用一个长字符串
在这里,您可以看到字符串格式只被调用一次,这意味着如果您讨论的是性能,那么这种方式会稍微好一点
编译此文件并检查IL。如果编译器将其优化为单个字符串,我不会感到惊讶。因此,没有运行时连接。在这种情况下,我可以想象编译器可能会优化这些concats,当然,如果其中有任何变量或格式,它就无法做到这一点。@wablab IL是什么?IL代表中间语言,您可以在此处查看有关它的更多信息:您有一个性能问题。您的性能测试显示了什么?如果您没有性能测试,并且担心性能,那么您如何知道代码是否太慢?很好的分析。这是调试版本还是发布版本?这有区别吗?只是想知道这是不是在发布版本中得到优化的东西之一。@wablab都是发布版本