且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中添加换行符

更新时间:2023-02-09 09:52:03

使用Environment.NewLine方法:

http://www.dotnetperls.com/newline [ ^ ]
Use the Environment.NewLine method:
http://www.dotnetperls.com/newline[^]


System.Envirement.NewLine是您的解决方案。参见示例:

http://www.dotnetperls.com/newline [ ^ ]
System.Envirement.NewLine is your solution. See example:
http://www.dotnetperls.com/newline[^]


两种方式:

1.尽可能将单个邮件分开,然后在结尾将它们组合一次:

Two ways:
1. Keep the individual message separate as long as possible and then combine them once at "the end":
var operationResult = new BO.OperationResult();
 List<string> messages = new List<string>();
// Physical Location Required
if (string.IsNullOrWhiteSpace(physicalLocationDesc))
{
  operationResult.Successful = false;
  messages.Add("A location is required as part of the entry");
}
// Type of Connection Desc. Required
if (string.IsNullOrWhiteSpace(typeOfConnectionID))
{
  operationResult.Successful = false;
  messages.Add("A description for the connection type is required.");
}
// Password change frequency desc. required
if (string.IsNullOrWhiteSpace(passwordChangeFrequency))
{
  operationResult.Successful = false;
  messages.Add("Please enter a description for the Password Change Frequency");
}
// etc...
operationResult.Message = string.Join(Environment.NewLine, messages);



2.使用 StringBuilder


2. Use a StringBuilder:

var operationResult = new BO.OperationResult();
 StringBuilder messages = new StringBuilder();
string sep = string.Empty;
// Physical Location Required
if (string.IsNullOrWhiteSpace(physicalLocationDesc))
{
  operationResult.Successful = false;
  messages.Append(sep).Append("A location is required as part of the entry");
  sep = Environment.NewLine;
}
// Type of Connection Desc. Required
if (string.IsNullOrWhiteSpace(typeOfConnectionID))
{
  operationResult.Successful = false;
  messages.Append(sep).Append("A description for the connection type is required.");
  sep = Environment.NewLine;
}
// Password change frequency desc. required
if (string.IsNullOrWhiteSpace(passwordChangeFrequency))
{
  operationResult.Successful = false;
  messages.Append(sep).Append("Please enter a description for the Password Change Frequency");
  sep = Environment.NewLine;
}
// etc...
operationResult.Message = messages.ToString();