简体   繁体   English

发布版本中的Debug.WriteLine

[英]Debug.WriteLine in release build

有没有办法在发布版本中使用Debug.WriteLine而不定义DEBUG

No, but you can use the Trace in release by defining TRACE and using Trace.WriteLine. 不,但您可以通过定义TRACE并使用Trace.WriteLine.来使用Trace in release Trace.WriteLine. Have a look here: 看看这里:

https://support.microsoft.com/en-us/help/815788/how-to-trace-and-debug-in-visual-c https://support.microsoft.com/en-us/help/815788/how-to-trace-and-debug-in-visual-c

No. If you don't define the DEBUG preprocessor symbol, any calls to Debug.* will be removed by the compiler due to the [Conditional("DEBUG")] attribute being applied. 否。如果未定义DEBUG预处理程序符号,则由于应用了[Conditional("DEBUG")]属性,编译器将删除对Debug.*任何调用。

You might want to consider Trace.WriteLine or other logging techniques though. 您可能想要考虑Trace.WriteLine或其他日志记录技术。

While you still have to define DEBUG - you don't have to do it assembly wide. 虽然你仍然需要定义DEBUG - 你不必在程序集范围内进行。 You can define it only in the source files that you want. 您只能在所需的源文件中定义它。 So if you want debug logging from a particular class you can define DEBUG just for that source file. 因此,如果您希望从特定类进行调试日志记录,则可以仅为该源文件定义DEBUG。

#define DEBUG
using System.Diagnostics;

...

class Logger
{
    void Log( string msg ){ Debug.WriteLine( msg ); }
}

Yes. 是。 You can, as mentioned in the above comments use TRACE, or without defining any compile time constants, by using Expression Trees. 您可以使用表达式树,如上面的注释中所述,使用TRACE,或者不定义任何编译时常量。

        var p = Expression.Parameter(typeof(string), "text");
        var callExp =
            Expression.Call(
              typeof(System.Diagnostics.Debug).GetRuntimeMethod(
                   "WriteLine", new [] { typeof(string) }),
              p);
        Action<string> compiledAction = Expression.Lambda<Action<string>>(
                                         callExp, p)
                                         .Compile();

After this, you can invoke the Debug.WriteLine anytime, by calling 在此之后,您可以通过调用随时调用Debug.WriteLine

        compiledAction("Debug text");

You're essentially tricking the compiler by not having a static method call, but instead dynamically constructing it at run-time. 您实际上是通过不进行静态方法调用来欺骗编译器,而是在运行时动态构造它。

There is no performance-hit since, the action is compiled and re-used. 由于没有性能影响,因此编译并重新使用该操作。

This is how I wrote a DebugLogger in SharpLog. 这就是我在SharpLog中编写DebugLogger的方法。

You may take a look at the source code here, if it interests you: https://github.com/prasannavl/SharpLog/blob/master/SharpLog/DebugLogger.cs 如果您感兴趣,可以在这里查看源代码: https//github.com/prasannavl/SharpLog/blob/master/SharpLog/DebugLogger.cs

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

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