简体   繁体   English

如何在调试时调试Debug.WriteLine()和在.NET / C#中以发布模式在Console.WriteLine()之间切换#

[英]How to switch between Debug.WriteLine() at debug and Console.WriteLine() in release mode in .NET/C#

In my C# code I would like to wrap Debug.WriteLine() and Console.WriteLine() into one function, so that it targets the debug window in debug mode and console in release mode. 在我的C#代码中,我想将Debug.WriteLine()Console.WriteLine()包装到一个函数中,以便它在调试模式下以调试窗口为目标,在发布模式下以控制台为目标。 What is the best way to achieve it? 实现它的最佳方法是什么? I am new to C#. 我是C#的新手。 Thanks. 谢谢。

Look at the System.Diagnostics.Trace class. 查看System.Diagnostics.Trace类。

Trace includes a WriteLine() method similar to that on the Debug and Console classes, and supports attaching/detaching various listeners at runtime or via config file, such as the ConsoleTraceLister , DefaultTraceListner (for Debug), the TextWriterTraceListener (for files), the EventLogTraceListener , or you can create your for writing to places like database tables or syslogd aggregators. Trace包含类似于Debug和Console类的WriteLine()方法,并支持在运行时或通过配置文件附加/分离各种侦听器,例如ConsoleTraceListerDefaultTraceListner (用于Debug), TextWriterTraceListener (用于文件), EventLogTraceListener ,或者您可以创建用于写入数据库表或syslogd聚合器等位置的文件。

You can just about change every current call to Debug or Console to use Trace instead, and just set the listeners you want to use. 您可以将每个当前调用更改为Debug或Console以改为使用Trace,并只设置要使用的侦听器。 Note that the Trace methods are missing a few formatting features, but I think the configurable output source more than makes up for it. 请注意,Trace方法缺少一些格式化功能,但我认为可配置的输出源可以弥补它。

Always use Debug.WriteLine and add these lines to the beginning of your program: 始终使用Debug.WriteLine并将这些行添加到程序的开头:

#if !DEBUG
            var listeners = new TraceListener[] { new TextWriterTraceListener(Console.Out) };
            Debug.Listeners.AddRange(listeners);
#endif

In addition to Joel's answer, another very simple solution would be this: 除了乔尔的答案,另一个非常简单的解决方案是:

private void writeLine(String s)
{

    #if DEBUG
        Debug.WriteLine(s);
    #else
        Console.WriteLine(s);
    #endif
}

This uses preprocessor directives so that it will not write to console except in Release mode. 这使用预处理程序指令,因此除了在发布模式下它不会写入控制台。 Note, it's slightly redundant as all Debug calls are removed during a Release build anyway, even without the preprocessor directive. 注意,它有点多余,因为即使没有预处理器指令,在Release版本中也会删除所有Debug调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM