在C#6一长串插线 [英] Long string interpolation lines in C#6

查看:94
本文介绍了在C#6一长串插线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现,而当考虑到一般首选列的限制应用​​到我的现有代码库的字符串格式来电,串插是非常好的,串迅速成为一条线太长。特别是当进行插值表达式是复杂的。与格式字符串你有,你可以拆分成多行变量列表。

 无功海峡=的String.Format(一些文字{0}更多文本{1},
OBJ1。财产,
obj2.property);



有没有人有分手这些线路中的任何首选方式?



我想你可以这样做:

 无功海峡= $一些文字{} obj1.property + 
更多的文字{obj2.property};


解决方案

您的可以的断行成多行,但我不会说的语法看起来不错了。



您需要使用 $ @ 语法使用插值的逐字的字符串,可以将里面的新行 {... } 参数,如:

 字符串s = $ @这是所有{
10
},将是一个长{
DateTime.Now
}行;

上面的字符串将不包含任何新行和实际上有这样的内容:




这是所有10个将是一个长2015年8月1日23.49.47线。




(注意,挪威格式)



现在,话说回来,我就不会停止使用的String.Format 。在我看来,其中的一些字符串表达式插值看起来确实不错,但更复杂的开始变得很难看。考虑到,除非你使用 FormattableString ,代码会被编译成一个调用的String.Format 无论如何,我会说保持与的String.Format 要去的地方很有道理。


I've found that while string interpolation is really nice when applied to my existing code base's string Format calls, given the generally preferred column limit, the string rapidly becomes too long for a single line. Especially when the expressions being interpolated are complex. With a format string you have a list of variables that you can split into multiple lines.

var str = string.Format("some text {0} more text {1}",
    obj1.property,
    obj2.property);

Does anyone have any preferred means of breaking up these lines?

I suppose you could do something like:

var str = $"some text { obj1.property }" +
  " more text { obj2.property };

解决方案

You can break the line into multiple lines, but I wouldn't say the syntax looks nice any more.

You need to use the $@ syntax to use an interpolated verbatim string, and you can place newlines inside the {...} parameters, like this:

string s = $@"This is all {
    10
    } going to be one long {
    DateTime.Now
    } line.";

The string above will not contain any newlines and will actually have content like this:

This is all 10 going to be one long 01.08.2015 23.49.47 line.

(note, norwegian format)

Now, having said that, I would not stop using string.Format. In my opinion some of these string interpolation expressions looks really good, but more complex ones starts to become very hard to read. Considering that unless you use FormattableString, the code will be compiled into a call to String.Format anyway, I would say keep going with String.Format where it makes sense.

这篇关于在C#6一长串插线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆