如何在多行上分割WriteLine?

时间:2011-04-28 15:35:06

标签: c#

这是我尝试过的语法示例,不想使用\n

Console.WriteLine("x"
                  "x"
                  "x"
                  "x"
                  "x");

一次通话应该产生:

x  
x  
x  
x  
x

8 个答案:

答案 0 :(得分:10)

一个调用不应该产生这个,因为你有两个字符串文字。事实上,这甚至都不会编译......

尝试:

Console.WriteLine("x\nx");

或者更糟糕的是:

Console.WriteLine(@"x
x");

答案 1 :(得分:5)

如果您有一组项目并希望将它们全部写在不同的行上,这始终是一个选项:

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"));

答案 2 :(得分:4)

你可以轻松使用@引用的字符串文字,如:

Console.WriteLine(@"X
X
X
X
X
X");

答案 3 :(得分:3)

试试这个:

Console.WriteLine(@"x
x
x
something
    notice this respects identation");

答案 4 :(得分:0)

不是那么容易,因为WriteLine只接受一个输入parm,或者带有格式化选项的parm,所以

Console.WriteLine("x\nx"); 

or

Console.WriteLine("{0}\n{1}\n{2}","x","x","x");  

\n是'换行'转义字符

(3 x的第二个示例格式)

你可以考虑多个WriteLines,每个'x'一个

答案 5 :(得分:0)

另一种选择是这样的。 (虽然我认为正确的答案是使用\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);
}

答案 6 :(得分:0)

以防万一你正在寻找某种方法来写出每个参数不同行的许多参数。下面是几个选项:

/// <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);
            }
        }
    }

答案 7 :(得分:-1)

您只需调用Write:

,而不是调用WriteLine
Console.Write("x");
Console.Write(Environment.NewLine);
Console.Write("x");