Cor*_*ory 34 c# string coding-style code-formatting
有没有一种不错的方法在C#中声明一个长单行字符串,这样在编辑器中声明和/或查看字符串并非不可能?
我知道的选项是:
1:让它运行.这很糟糕,因为你的字符串走到了屏幕右侧,让开发人员阅读消息时不得不烦人滚动和阅读.
string s = "this is my really long string. this is my really long string. this is my really long string. this is my really long string. this is my really long string. this is my really long string. this is my really long string. this is my really long string. ";
Run Code Online (Sandbox Code Playgroud)
2:@ +换行.这在代码中看起来不错,但是为字符串引入了换行符.此外,如果您希望它在代码中看起来不错,不仅会获得换行符,而且还会在字符串的每一行的开头处获得尴尬的空格.
string s = @"this is my really long string. this is my long string.
this line will be indented way too much in the UI.
This line looks silly in code. All of them suffer from newlines in the UI.";
Run Code Online (Sandbox Code Playgroud)
3:"" + ...这样可以正常工作,但打字非常令人沮丧.如果我需要在某处添加半行的文本,我必须更新所有类型的+并移动文本.
string s = "this is my really long string. this is my long string. " +
"this will actually show up properly in the UI and looks " +
"pretty good in the editor, but is just a pain to type out " +
"and maintain";
Run Code Online (Sandbox Code Playgroud)
4 : string.format or string.concat. 基本上与上面相同,但没有加号.具有相同的好处和缺点.
真的没办法做得好吗?
小智 62
有一种方法.把你的长字符串放在资源中.你甚至可以把很长的文本放在那里,因为它是文本的所在.直接在代码中使用它们是一种非常糟糕的做法.
如果使用Visual Studio
Tools > Options > Text Editor > All Languages > Word Wrap
Run Code Online (Sandbox Code Playgroud)
我相信任何其他文本编辑器(包括记事本)都能够做到这一点!
这取决于字符串将如何使用.这里的所有答案都是有效的,但背景很重要.如果要记录长字符串"s",则应该使用日志记录保护测试,例如此Log4net示例:
if (log.IsDebug) {
string s = "blah blah blah" +
// whatever concatenation you think looks the best can be used here,
// since it's guarded...
}
Run Code Online (Sandbox Code Playgroud)
如果要向用户显示长字符串s,那么Developer Art的答案是最佳选择......那些应该在资源文件中.
对于其他用途(生成SQL查询字符串,写入文件[但再次考虑这些资源]等等),在这里你不仅仅是文字连接,请考虑像Wael Dalloul建议的StringBuilder ,特别是如果你的字符串可能会风在一个函数中,可能在遥远的未来的某个日期,在一个时间关键的应用程序中被调用很多次(所有这些调用加起来).我这样做,例如,在构建SQL查询时,我有参数是变量.
除此之外,不,我不知道任何看起来很漂亮且易于打字的东西(尽管自动换行提示是一个好主意,它可能无法很好地转换为差异工具,代码打印输出或代码审查工具).那些是休息.(我个人使用加号方法为我们的打印输出和代码审查制作整齐的线条).
如果你真的想在代码中使用这个长字符串,并且你真的不想输入end-quote-plus-begin-quote,那么你可以试试这样的东西.
string longString = @"Some long string,
with multiple whitespace characters
(including newlines and carriage returns)
converted to a single space
by a regular expression replace.";
longString = Regex.Replace(longString, @"\s+", " ");
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用StringBuilder:
StringBuilder str = new StringBuilder();
str.Append("this is my really long string. this is my long string. ");
str.Append("this is my really long string. this is my long string. ");
str.Append("this is my really long string. this is my long string. ");
str.Append("this is my really long string. this is my long string. ");
string s = str.ToString();
Run Code Online (Sandbox Code Playgroud)
您还可以使用:文本文件,资源文件,数据库和注册表.