Debug vs Trace in C#
As I understand statements like Debug.WriteLine()
will not stay in the code in the Release build. On the other hand Trace.WriteLine()
will stay in the code in the Release build.
What is controling this behaviour? Does the C# compiler ignores everything from the System.Diagnostics.Debug
cla开发者_JAVA技巧ss when the DEBUG
is defined?
I am just trying to understand the internals of C# and just curious.
These methods use the ConditionalAttribute
to designate when they should be included.
When DEBUG
is specified as a #define
, via the command line or the system environment (set DEBUG = 1
in the shell), a method marked with [Conditional("DEBUG")]
will be included by the compiler. When DEBUG
is not included, those methods and any calls to them will be omitted. You can use this mechanism yourself to include methods under certain circumstances and it is also used to control the Trace
calls like Trace.WriteLine
(this uses the TRACE
define).
This is due to ConditionalAttribute
; the compiler ignores calls to methods marked as conditional unless that symbol is defined.
You can have your own:
[Conditional("BLUE")]
void Bar() {...}
which will only be called when BLUE is defined.
Note that there are some restrictions, to make "definite assignment" work:
- no return value
- no out parameters
(the same restrictions apply to partial
methods for similar reasons)
精彩评论