Why doesn't Debug.WriteLine work without the DEBUG constant?

落爺英雄遲暮 提交于 2019-12-13 08:46:31

问题


I ran into an issue where someone had apparently disabled the DEBUG and TRACE constants on a C# .NET project I was working on, so my calls to Debug.WriteLine were having no effect. (No debug output was shown in the output.) After re-enabling them as described here, I started seeing my output.

Knowing how to fix it is helpful, but my question is why? As far as I understand, DEBUG is a compile time constant, and the Debug class is already compiled when I build my project. So how are my calls to Debug.WriteLine skipped; shouldn't they be compiled like all my other code?

I can think of a few possible ways this could happen:

  • MS implemented some special "feature" in the compiler to remove these calls without the constant
  • Visual Studio sets up the debugger such that it does or doesn't listen based on this project setting for debug output when it runs
  • Debug has some crazy code that examines the calling assembly for some kind of flag set at compile time

MS's documentation indicates that this is expected behavior, but I haven't been able to track down any documentation about how it actually works. It could also be something that never even occurred to me, of course.

So how does it work?


回答1:


Have a look at the Conditional attribute... It causes the method call to be ignored at JIT-time if the specified symbol is not defined. Most System.Diagnostic.Debug methods are defined using this attribute and the value "DEBUG" (see reference source for example), hence the calls don't occur if the DEBUG symbol is not defined at JIT-time.




回答2:


Debug.WriteLine(..) calls are removed by the compiler if the DEBUG constant is not set at the time you compile your code.

One way to simulate this in your code is by using #if DEBUG, for example:

#if DEBUG 
    // This portion of the code will only exist in code compiled with the DEBUG constant set.
#end if

Another way is to add the ConditionalAttribute [Conditional("DEBUG")] to the top of your methods, which is what the Debug class does for WriteLine(..).

The exact details can be found at the following link on MSDN in the ConditionalAttribute documentation: https://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute(v=vs.110).aspx



来源:https://stackoverflow.com/questions/37668476/why-doesnt-debug-writeline-work-without-the-debug-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!