Will #if RELEASE work like #if DEBUG does in C#?

前端 未结 11 1743
时光说笑
时光说笑 2020-11-30 17:39

In all the examples I\'ve seen of the #if compiler directive, they use \"DEBUG\". Can I use \"RELEASE\" in the same way to exclude code that I don\'t want to run when compi

相关标签:
11条回答
  • 2020-11-30 17:40

    I know this is an old question, but it might be worth mentioning that you can create your own configurations outside of DEBUG and RELEASE, such as TEST or UAT.

    If then on the Build tab of the project properties page you then set the "Conditional compilation symbols" to TEST (for instance) you can then use a construct such as

    #if (DEBUG || TEST )
        //Code that will not be executed in RELEASE or UAT
    #endif
    

    You can use this construct for specific reason such as different clients if you have the need, or even entire Web Methods for instance. We have also used this in the past where some commands have caused issues on specific hardware, so we have a configuration for an app when deployed to hardware X.

    0 讨论(0)
  • 2020-11-30 17:40

    You can create you own conditional compile-time symbols (any name you like). Go to the "project Build dialog", located in the project properties box, menu option: Project->[projectname] Properties...

    You can also define them "at the top of the C# code file". Like:

    #define RELEASE
    // or
    #undef RELEASE
    

    you can use the symbol in a #if statement:

    #if RELEASE
    // code ...
    #elif …
    // code ...
    #endif
    
    // or
    
    #if !RELEASE
    // code ...
    #endif
    
    0 讨论(0)
  • 2020-11-30 17:46

    RELEASE is not defined, but you can use

    #if (!DEBUG)
      ...
    #endif
    
    0 讨论(0)
  • 2020-11-30 17:50

    why not just

    #if RELEASE
    #undef DEBUG
    #endif
    
    0 讨论(0)
  • 2020-11-30 17:51

    On my VS install (VS 2008) #if RELEASE does not work. However you could just use #if !DEBUG

    Example:

    #if !DEBUG
    SendTediousEmail()
    #endif
    
    0 讨论(0)
  • 2020-11-30 17:51

    Whilst M4N's answer (#if (!DEBUG)) makes most sense, another option could be to use the preprocessor to amend other flag's values; e.g.

    bool isRelease = true;
    #if DEBUG
        isRelease = false;
    #endif
    

    Or better, rather than referring to whether we're in release or debug mode, use flags that define the expected behavior and set them based on the mode:

    bool sendEmails = true;
    #if DEBUG
        sendEmails = false;
    #endif
    

    This is different to using preprocessor flags, in that the flags are still there in production, so you incur the overhead of if (sendEmails) {/* send mails */} each time that code's called, rather than the code existing in release but not existing in debug, but this can be advantageous; e.g. in your tests you may want to call your SendEmails() method but on a mock, whilst running in debug to get additional output.

    0 讨论(0)
提交回复
热议问题