Debug.WriteLine in release build
Is there a way to use Debug.WriteLine
in a release build without defining开发者_如何学Python DEBUG
?
No, but you can use the Trace
in release by defining TRACE
and using Trace.WriteLine.
Have a look here:
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.
You might want to consider Trace.WriteLine
or other logging techniques though.
While you still have to define DEBUG - you don't have to do it assembly wide. 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.
#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.
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
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.
You may take a look at the source code here, if it interests you: https://github.com/prasannavl/SharpLog/blob/master/SharpLog/DebugLogger.cs
Debugger.Log(0, null, "Your string here");
could be an alternative, it is used internally by Debug.Write
and it also works in Release.
精彩评论