Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

c# - Long string interpolation lines in C#6

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 };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...