How to indent #if directives in code? [duplicate]

2020-02-11 03:34发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
How to force indentation of C# conditional directives?
Can visual studio automatically indent / format preprocessing directives?

In the following sample code there is a #if directive but notice the lack of indentation:

                else
                {
#if DEBUG
    Debug.Print(ex.Message);
#endif                    
                    return null;
                }

I know this is probably like this for some pure development practice, but honestly within VS.NET I do not care and would prefer it to align with my code. Is there a way to allow # directives be auto indented inline with the rest of the code in VS.NET?

Thanks!

回答1:

I tried to search something here:

Option -> Text Editor -> C#

but unfortunately it seems that visualstudio doesn't have anything built in which permit you to indent the preprocessor directives in that way. However googling I found this answer and it recommends to use StyleCop. Hope this helps you.



回答2:

I'm not sure you can do it with Visual Studio natively. You might have to use a plugin like StyleCop. See http://stylecop.codeplex.com/

I understand why you'd want the indentation done- because the conditional directives currently look quite messy. However, with the current indentation, the advantage is that it can be easily seen by someone who is reading your code. Since conditional directives can change the flow of your code by a great extent, it might be okay as it is right now. Otherwise, you have the plugin options :)



回答3:

I don't know of anything, but the # pragmas shouldn't be indented anyway, as they are not affected by the code. It's fine to indent the Debug.Print of course.