Visual Studio 2013 - 如何在控制台中查看输出?

3

我刚开始学习C#和VS,尝试使用Console.WriteLine(...)打印一行文字,但它只会在命令提示符中显示。有没有办法让输出显示在输出窗口中呢?

编辑:这是一个控制台应用程序。

另外,如何访问命令行以运行程序?我只能找到使用F5运行的方法,但如果需要输入参数,则无法使用此方法。


这是一个控制台应用程序。 - Aei
1
请澄清您的术语。您所说的“命令行”是指什么,比如“但它只出现在命令行中”。您所说的“控制台”是指什么,比如“有没有办法让输出显示在控制台中?”? - Kirk Woll
@Aei,尝试使用Debug.WriteLine(); - martynaspikunas
@martynaspikunas 编辑器似乎无法识别名称“Debug”。 - Aei
1
你需要解决命名空间问题。用鼠标右键点击 Debug 类,选择解决选项。 - martynaspikunas
显示剩余4条评论
4个回答

10

如果是控制台应用程序,Console.WriteLine会在控制台中写入内容。如果使用Debug.Print,则会将内容打印到底部的输出选项卡中。

如果想要添加命令行参数,可以在项目属性中找到。单击Project -> [YourProjectName] Properties... -> Debug -> Start Options -> Command line arguments。这里的文本将在运行应用程序时传递给应用程序。您也可以在构建后通过从bin\Releasebin\Debug文件夹中运行它来运行它,通过cmd或其他方式。我发现这样测试各种参数比每次设置命令行参数更容易。


2

我也遇到了这个问题,在使用VS2012的前两天。我的控制台输出在哪里?它一闪而过。像https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b这样的有用示例让我感到困惑。

确实,@martynaspikunas提供的方法是可以将Console.WriteLine()替换为Debug.WriteLine()以在IDE中查看输出。这样做很好,输出会一直保留在那里。

但有时你需要在现有代码的许多地方进行更改才能实现这一点。

我找到了一些替代方法...比如只需要使用一个

Console.ReadKey();

在 Program.cs 中?控制台将等待您,它可以滚动。
我也喜欢在我的 Winforms 上下文中使用控制台输出:
 class MyLogger : System.IO.TextWriter
    {
        private RichTextBox rtb;
        public MyLogger(RichTextBox rtb) { this.rtb = rtb; }
        public override Encoding Encoding { get { return null; } }
        public override void Write(char value)
        {
            if (value != '\r') rtb.AppendText(new string(value, 1));
        }
    }

在你的主表单类之后添加这个类。然后将它插入,使用以下重定向语句,在InitializeComponent()被调用后构造函数中:
 Console.SetOut(new MyLogger(richTextBox1));

由此,所有的Console.WriteLine()都会出现在richTextBox中。
有时我会使用它将输出重定向到List以便稍后报告Console,或将其转储到文本文件中。
注意:MyLogger代码片段是由Hans Passant在2010年发布的。 将控制台输出绑定到RichEdit

0
using System;
#region Write to Console
/*2 ways to write to console
 concatenation
 place holder syntax - most preferred
 Please note that C# is case sensitive language.
*/
#region
namespace _2__CShrp_Read_and_Write
{
    class Program
    {
        static void Main(string[] args)
        {

            // Prompt the user for his name
            Console.WriteLine("Please enter your name");

            // Read the name from console
            string UserName = Console.ReadLine();
            // Concatenate name with hello word and print
            //Console.WriteLine("Hello " + UserName);

            //place holder syntax
            //what goes in the place holder{0}
            //what ever you pass after the comma i.e. UserName
            Console.WriteLine("Hello {0}", UserName);
            Console.ReadLine();
        }
    }
}
I hope this helps

0

这里有一个简单的技巧,可以保留控制台及其输出:

int main ()
{
    cout << "Hello World" << endl ;

    // Add this line of code before your return statement and the console will stay up
    getchar() ;  

    return 0;
}

1
这个答案是错误的,因为它使用了C++,而OP要求的是C#。 - Bill Tür stands with Ukraine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接