C# - Console.WriteLine()没有显示第二个参数

时间:2016-02-18 22:15:33

标签: c# .net console

当我使用不同的方法制作2个bool变量并且我尝试使用Console.WriteLine()方法显示它们时,处理C#Basic数据类型时,显示了第一个变量但是没有显示第二个变量。 我知道替代方法是通过在变量之间使用+符号或在Console.WriteLine中使用占位符语法来获得所需的输出,但我只是想知道原因,为什么第二个参数没有显示?如果有人知道原因,请回答。

这是我正在处理的代码。

        bool b1 = true;
        System.Boolean b2 = new System.Boolean();
        b2 = false;
        Console.WriteLine( b1.ToString() , b2.ToString() );

5 个答案:

答案 0 :(得分:7)

Console.WriteLine的作用为String.Format

  • 第一个参数:格式化字符串。
  • 第二到第n:要使用的参数 格式字符串。

这是你需要做的:

Console.WriteLine("{0} {1}", b1, b2);

答案 1 :(得分:1)

检查在.net框架和替代方案中写入重载函数的方法是:

Console.WriteLine(B1); Console.WriteLine(B2);

答案 2 :(得分:0)

以下是Console的官方文档。我认为您认为参数是(字符串,字符串),但它实际上是(字符串,对象)。

        // Summary:
        //     Writes the text representation of the specified object, followed by the current
        //     line terminator, to the standard output stream using the specified format
        //     information.
        //
        // Parameters:
        //   format:
        //     A composite format string (see Remarks).
        //
        //   arg0:
        //     An object to write using format.
        //
        // Exceptions:
        //   System.IO.IOException:
        //     An I/O error occurred.
        //
        //   System.ArgumentNullException:
        //     format is null.
        //
        //   System.FormatException:
        //     The format specification in format is invalid.
        public static void WriteLine(string format, object arg0);

答案 3 :(得分:0)

您要调用的重载旨在将格式字符串作为第一个参数,将格式字符串中使用的对象作为第二个参数。 https://msdn.microsoft.com/en-us/library/586y06yf(v=vs.110).aspx

你应该做的是两次调用Console.WriteLine:

Console.WriteLine(b1);
Console.WriteLine(b2);

答案 4 :(得分:-4)

这是您在计划中尝试做的事情:
 Console.WriteLine(b1.ToString(),b2.ToString());

第一个参数接受格式,第二个参数接受要显示的对象,在您的情况下,您提供要显示的对象,但在您的第一个(格式)参数中,您没有指定要显示的位置,它正在接收您的对象但无法要在控制台中显示它,因为你没有指定那个东西,在C#中你可以用几种不同的方式指定

Console.WriteLine(b1.ToString()+ " {0}", b2.ToString());
Console.WriteLine($"{b1.ToString()} {b2.ToString()}"); 
Console.WriteLine(b1.ToString() + " " + b2.ToString());
相关问题