C# how can I use #if to have different compile result for debug and release?

前端 未结 3 466
暗喜
暗喜 2021-02-10 05:26

In C++ we can use #ifdef to eliminate some debug statements when we release. C# is different from C++ in preprocessor. Can I still get the same result useing C# #if. We want to

3条回答
  •  感动是毒
    2021-02-10 05:50

    You can wrap code in:

    #if DEBUG
    
    // debug only code
    
    #endif
    

    However, I don't recommend this. It's often a better alternative to just make a method and flag it with the [Conditional("DEBUG")] attribute. See Conditional on MSDN for more details. This allows you to make debug only methods:

    [Conditional("DEBUG")]
    public void DebugPrint(string output) { // ... 
    }
    

    Then, you can call this normally:

    DebugPrint("Some message"); // This will be completely eliminated in release mode
    

提交回复
热议问题