繁体   English   中英

发布版本中的Debug.WriteLine

[英]Debug.WriteLine in release build

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

不,但您可以通过定义TRACE并使用Trace.WriteLine.来使用Trace in release Trace.WriteLine. 看看这里:

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

否。如果未定义DEBUG预处理程序符号,则由于应用了[Conditional("DEBUG")]属性,编译器将删除对Debug.*任何调用。

您可能想要考虑Trace.WriteLine或其他日志记录技术。

虽然你仍然需要定义DEBUG - 你不必在程序集范围内进行。 您只能在所需的源文件中定义它。 因此,如果您希望从特定类进行调试日志记录,则可以仅为该源文件定义DEBUG。

#define DEBUG
using System.Diagnostics;

...

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

是。 您可以使用表达式树,如上面的注释中所述,使用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();

在此之后,您可以通过调用随时调用Debug.WriteLine

        compiledAction("Debug text");

您实际上是通过不进行静态方法调用来欺骗编译器,而是在运行时动态构造它。

由于没有性能影响,因此编译并重新使用该操作。

这就是我在SharpLog中编写DebugLogger的方法。

如果您感兴趣,可以在这里查看源代码: https//github.com/prasannavl/SharpLog/blob/master/SharpLog/DebugLogger.cs

暂无
暂无

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

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