[英]Why doesn't Debug.WriteLine work without the DEBUG constant?
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. 我遇到一个问题,就是有人显然在我正在处理的C#.NET项目上禁用了
DEBUG
和TRACE
常量,因此我对Debug.WriteLine
调用无效。 (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. 据我了解,
DEBUG
是一个编译时间常量 ,并且在构建项目时已经编译了Debug
类。 So how are my calls to Debug.WriteLine
skipped; 因此,如何跳过对
Debug.WriteLine
调用; shouldn't they be compiled like all my other code? 难道不应该像我所有其他代码一样编译它们吗?
I can think of a few possible ways this could happen: 我可以想到可能发生的几种方式:
Debug
has some crazy code that examines the calling assembly for some kind of flag set at compile time Debug
有一些疯狂的代码,可以在编译时检查调用程序集是否设置了某种标志 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. MS的文档表明这是预期的行为,但是我无法找到有关其实际工作方式的任何文档。 It could also be something that never even occurred to me, of course.
当然,这也可能是我从未发生过的事情。
So how does it work? 那么它是怎样工作的?
Debug.WriteLine(..)
calls are removed by the compiler if the DEBUG constant is not set at the time you compile your code. 如果在编译代码时未设置DEBUG常量,则编译器将删除
Debug.WriteLine(..)
调用。
One way to simulate this in your code is by using #if DEBUG
, for example: 在您的代码中对此进行模拟的一种方法是使用
#if DEBUG
,例如:
#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(..)
. 另一种方法是将
ConditionalAttribute
[Conditional("DEBUG")]
到方法的顶部,这是Debug类对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 确切的详细信息可以在ConditionalAttribute文档中的MSDN上的以下链接中找到: https : //msdn.microsoft.com/zh-cn/library/system.diagnostics.conditionalattribute(v=vs.110).aspx
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. 看一下Conditional属性 ...如果未定义指定的符号,它将导致在JIT时忽略方法调用。 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.
大多数System.Diagnostic.Debug方法是使用此属性和值“ DEBUG”定义的(例如,请参见参考源 ),因此,如果未在JIT时定义DEBUG符号,则不会发生调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.