有没有一种方法可以在不定义 DEBUG的情况下在发布版本中使用 Debug.WriteLine?
DEBUG
Debug.WriteLine
没有。如果您没有定义 DEBUG预处理器符号,那么由于应用了 [Conditional("DEBUG")]属性,编译器将删除对 Debug.*的任何调用。
[Conditional("DEBUG")]
Debug.*
不过,您可能需要考虑 Trace.WriteLine或其他日志记录技术。
Trace.WriteLine
没有,但是你可以通过定义 TRACE和使用 Trace.WriteLine.来使用发行版中的 Trace:
TRACE
Trace.WriteLine.
Trace
Https://support.microsoft.com/en-us/help/815788/how-to-trace-and-debug-in-visual-c
虽然你仍然必须定义 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
Debugger.Log(0, null, "Your string here");可能是另一种选择,它是由 Debug.Write在内部使用,它也在发布中工作。
Debugger.Log(0, null, "Your string here");
Debug.Write