如何将WriteLine分割为多行
本文关键字:分割 WriteLine | 更新日期: 2023-09-27 17:53:49
这是我尝试过的语法示例,不想使用'n
。
Console.WriteLine("x"
"x"
"x"
"x"
"x");
一个调用应该产生:
<>之前xxxxx一次调用不应该产生这种结果,因为您有两个字符串字面值。事实上,这甚至不能编译…
试题:
Console.WriteLine("x'nx");
或者更糟:
Console.WriteLine(@"x
x");
您可以简单地使用@引号字符串字面值,如:
Console.WriteLine(@"X
X
X
X
X
X");
如果您有一个项目集合,并且希望将它们全部写在单独的行上,那么这总是一个选项:
var myItems = new[] { "x", "x", "x", "x", "x" };
Console.WriteLine(String.Join(Environment.NewLine, myItems));
// or without the collection
Console.WriteLine(String.Join(Environment.NewLine, "x", "x", "x", "x", "x"));
Try This:
Console.WriteLine(@"x
x
x
something
notice this respects identation");
不太容易,因为WriteLine只接受一个输入parm,或者一个带有格式化选项的parm,所以要么
Console.WriteLine("x'nx");
or
Console.WriteLine("{0}'n{1}'n{2}","x","x","x");
'n
是'换行'转义字符
(第二个示例格式为3 x)
你可以考虑多个writeline,每个'x'一个?
另一个选项是这样的。(虽然我认为正确的答案是使用'n
)
static void Main(string[] args)
{
WriteMulti("A", "B", "C", "D", "E", "F", "G");
Console.ReadLine();
}
static void WriteMulti(params string[] args)
{
foreach (string arg in args)
Console.WriteLine(arg);
}
以防万一您正在寻找某种方法将多个参数写入每个参数的不同行。下面是几个选项:
/// <example>
/// Console.WriteLine(new LinesItem("X", "X"));
/// </example>
public class LinesItem
{
private readonly string _lineSeparator;
private readonly object[] _items;
public LinesItem(params object[] items) : this("'r'n", items)
{
_items = items;
}
public LinesItem(string lineSeparator, params object[] items)
{
_lineSeparator = lineSeparator;
_items = items;
}
public override string ToString()
{
return String.Join(_lineSeparator, _items.Select(x => x.ToString()).ToArray());
}
}
//OR
/// <summary>
/// Because System.Console is a static class you cannot use Extension methods which would
/// have been nice. Instead you can simply make another static class to do extra things.
/// </summary>
/// <example>
/// ExtendedConsole.WriteLines("X", "X");
/// </example>
public static class ExtendedConsole
{
public static void WriteLines(params object[] items)
{
foreach(var item in items)
{
Console.WriteLine(item);
}
}
}
不调用WriteLine,只需调用Write:
Console.Write("x");
Console.Write(Environment.NewLine);
Console.Write("x");