简体   繁体   English

仅在使用 Visual Studio 调试时执行代码

[英]Execute code only while debugging with Visual Studio

Is it possible to run specific code only when I am debugging the program via the debugging tools of Visual Studio?只有当我通过 Visual Studio 的调试工具调试程序时,才能运行特定代码吗?

If I use #if DEBUG or Conditional(“DEBUG”) the code is still triggered when running the .exe in the /Debug directory.如果我使用#if DEBUGConditional(“DEBUG”) ,则在 /Debug 目录中运行 .exe 时仍会触发代码。

The #if DEBUG is for Conditional Compilation, it does not affect execution at runtime. #if DEBUG用于条件编译,它不影响运行时的执行。

Instead use Debugger.IsAttached to branch at runtime. 而是使用Debugger.IsAttached在运行时分支。

Ok I finally found the answer: 好吧,我终于找到了答案:

if (Debugger.IsAttached) is exactly what I needed. 如果(Debugger.IsAttached)正是我需要的。

Just to make it clear, the statements beginning with a hashtag are pre-processor directives. 为了清楚起见,以井号标签开头的语句是预处理程序指令。 These directives are not present in the Translation Unit; 这些指令在翻译部门中不存在; thus these conditional statements do not exist in the compiled file. 因此,这些条件语句在编译文件中不存在。

EDIT It seems that this whole translation unit thing doesn't apply for C# 编辑似乎整个翻译单元都不适用于C#

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM