What is the usage of #if DEBUG pre-processor directive in C#? When must we use this?

前端 未结 5 915
梦谈多话
梦谈多话 2021-01-11 10:55

What is the usage of #if DEBUG pre-processor directive in C#? When must we use this?

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-11 11:10

    When compiling you can set Compiler flags which you can use to put code into those directives. That code will not be compiled and never ends up in the final assembly output. DEBUG is one of the predefined ones, but you can use your own.

    As an example of usage: In one of the current developments we use a compiler flag to state whether to use A login mask to log in a user, or whether login should occur automatically with the current principal. The second mode is only for the developers to e.g. debug quicker without having to log in.

    Another example: In some mono code you will see flags. In this case code may be compiled differently when e.g. targetting a different framework, as it uses classes that may not exist in earlier releases.

    Related to this is the Conditional-Attribute with which you can mark a method. If said flag isn't set, calls to the method will not be performed. The method still ends up in the IL, but calls will be removed.

    Check for example following code:

    var mthods = typeof (Debug).GetMethods().Where(mi => mi.Name.Equals("WriteLine")).ToList();
    var attribs = mthods[0].GetCustomAttributes(true);
    

    You will notice that the Debug.WriteLine method has the Conditional attribute applied to it: Calls to it will be removed when you compile WITHOUT the DEBUG compiler flag.

提交回复
热议问题