在C#代码后面的页面中添加换行符

我用C#编写了一个超出页面宽度的代码,所以我希望根据我的格式将它分成下一行。 我试图搜索很多东西来换行,但是没能找到。

在VB.NET中,我使用’_’表示换行符,与C#中使用的方法相同? 我想破坏一个字符串。

在此先感谢Shantanu Gupta

选项A:将几个字符串文字连接成一个:

 string myText = "Looking up into the night sky is looking into infinity" + " - distance is incomprehensible and therefore meaningless."; 

选项B:使用单个多行字符串文字:

 string myText = @"Looking up into the night sky is looking into infinity - distance is incomprehensible and therefore meaningless."; 

使用选项B,换行符将成为保存到变量myText中的字符串的一部分。 这可能是,也可能不是,你想要的。

在C#中,没有像VB.NET那样的“新行”字符。 代码的逻辑“行”的结尾用’;’表示。 如果你希望在多行上打破代码行,只需点击回车符(或者如果你想以编程方式添加它(对于以编程方式生成的代码),请插入’Environment.NewLine’或’\ r \ n’。

编辑:响应您的注释:如果您希望在多行(即以编程方式)中断字符串,则应插入Environment.NewLine字符。 这将考虑环境以创建行结束。 例如,许多环境(包括Unix / Linux)仅使用NewLine字符(\ n),但Windows同时使用回车符和换行符(\ r \ n)。 所以要打破一个字符串,你会使用:

 string output = "Hello this is my string\r\nthat I want broken over multiple lines." 

当然,这只会对Windows有利,所以在我因为不正确的练习而受到抨击之前你应该这样做:

 string output = string.Format("Hello this is my string{0}that I want broken over multiple lines.", Environment.NewLine); 

或者,如果要在IDE中拆分多行,则可以执行以下操作:

 string output = "My string" + "is split over" + "multiple lines"; 

在启动字符串之前使用@符号。 喜欢

 string s = @"this is a really long string and this is the rest of it"; 

如果我正确地理解了这一点,你应该能够将字符串分解为子串以实现此目的。

即:

 string s = "this is a really long string" + "and this is the rest of it"; 
  result = "Minimum MarketData"+ Environment.NewLine + "Refresh interval is 1"; 

C#没有明确的换行符。 您的语句以分号结尾,因此您可以在多行中跨越语句。 这些都是一样的:

 public string GenerateString() { return "abc" + "def"; } public string GenerateString() { return "abc" + "def"; } 

C#代码可以在几乎任何合成构造的行之间拆分,而不需要’_’样式构造。

例如

 foo. Bar( 42 , "again"); 

您需要做的就是添加\ n或写入文件go \ r \ n。

例子:

说你想写鸭子(换行)牛这是你怎么做的Console.WriteLine(“duck \ n cow”);

编辑:我想我不明白这个问题。 您可以使用

 @"duck cow".Replace("\r\n", "") 

作为代码中的换行符,产生\ r \ n使用Windows。

  dt = abj.getDataTable( "select bookrecord.userid,usermaster.userName, " +" book.bookname,bookrecord.fromdate, " +" bookrecord.todate,bookrecord.bookstatus " +" from book,bookrecord,usermaster " +" where bookrecord.bookid='"+ bookId +"' " +" and usermaster.userId=bookrecord.userid " +" and book.bookid='"+ bookId +"'"); 

伙计们..代码背后的长字符串使用资源!!

另外..你不需要_用于C#中的代码行中断。 在VB中,代码行以换行符(或’:’)结尾,使用_会告诉解析器它还没有到达行的末尾。 C#中的代码行以’;’结尾 所以你可以使用换行符来格式化你的代码。

字符串是不可变的,所以使用

 public string GenerateString() { return "abc" + "def"; } 

会降低你的性能 – 每个值都是一个字符串文字,必须在运行时连接 – 如果你重用方法/属性/任何很多的坏消息……

将您的字符串文字存储在资源中是个好主意……

 public string GenerateString() { return Resources.MyString; } 

这样它可以本地化,代码很整洁(虽然性能非常糟糕)。