In C#, what's the best way to spread a single-

2019-02-05 12:08发布

Suppose that you have a lengthy string (> 80 characters) that you want to spread across multiple source lines, but don't want to include any newline characters.

One option is to concatenate substrings:

string longString = "Lorem ipsum dolor sit amet, consectetur adipisicing" +
    " elit, sed do eiusmod tempor incididunt ut labore et dolore magna" +
    " aliqua. Ut enim ad minim veniam";

Is there a better way, or is this the best option?

Edit: By "best", I mean easiest for the coder to read, write, and edit. For example, if you did want newlines, it's very easy to look at:

string longString =
@"Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam";

I am wondering if there is something just as clean when you don't want newlines.

7条回答
迷人小祖宗
2楼-- · 2019-02-05 12:46

You could use multiple consts and then combine them into one big string:

const string part1 = "part 1";
const string part2 = "part 2";
const string part3 = "part 3";
string bigString = part1 + part2 + part3;

The compiler will "fold" these constants into one big string anyway, so there is no runtime cost at all to this technique as compared to your original code sample.

There are a number of advantages to this approach:

  1. The substrings can be easily reused in other parts of the application.
  2. The substrings can be defined in multiple files or types, if desired.
查看更多
登录 后发表回答