简体   繁体   中英

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?

If I use #if DEBUG or Conditional(“DEBUG”) the code is still triggered when running the .exe in the /Debug directory.

The #if DEBUG is for Conditional Compilation, it does not affect execution at runtime.

Instead use Debugger.IsAttached to branch at runtime.

Ok I finally found the answer:

if (Debugger.IsAttached) is exactly what I needed.

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#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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