Is the #region directive really useful in .NET?

2019-02-11 16:38发布

After maintaining lots of code littered with #region (in both C# and VB.NET), it seems to me that this construct is just a bunch of "make work" for the programmer. It's work to PUT the dang things into the code, and then they make searching and reading code very annoying.

What are the benefits? Why do coders go to the extra trouble to put this in their code.

Make me a believer!

17条回答
霸刀☆藐视天下
2楼-- · 2019-02-11 16:52

I hate the over-use of these. The only think I find them useful for is hiding away things you probably never want to see again. Then again, those things should probably be off in a library somewhere.

查看更多
做自己的国王
3楼-- · 2019-02-11 16:57

A similar question has already been asked.

but...

I would say not anymore. It was originally intended to hide generated code from WinForms in early versions of .NET. With partial classes the need seems to go away. IMHO it gets way overused now as an organizational construct and has no compiler value whatsoever. It's all for the IDE.

查看更多
Rolldiameter
4楼-- · 2019-02-11 16:57

http://www.rauchy.net/regionerate/ - Automatically regionised your code ;)

I'm a fan of regions for grouping sections of large classes, say all the properties together, all constances, etc. I'm someone who's constantly collapsing code I don't need to see at that time so I love regions for that.

Also I find regions really useful when implementing interfaces, particularly multiple interfaces. I can group each interfaces methods, properties, events, etc so it's easier at a glance to see what method belongs to what interface.

查看更多
疯言疯语
5楼-- · 2019-02-11 16:57

Going on with what has been previously said by Russell Myers, if you learn how to refactor your code properly (a skill proficient developers must learn), there really isn't too much of a need for regions.

A couple of weeks ago I thought regions were great because they allowed me to hide my fat code, but after exercising my code skills I was able to make it slimmer and now I fit into a size 7 class (someone should SO make that a measurement for refactoring in the future! :P)

查看更多
欢心
6楼-- · 2019-02-11 16:59

I use them all the time. Again, like anything else, they can be used for both evil and good, and can certainly be the hallmark of bad design, but they can be used to help organize code very well.

#region Properties

#region Update Section

#region Accessors

Certainly you should avoid Jeff's example of

#Sweep under carpet

What I find odd about them, as Jeff pointed out, is that they are a compiler preprocessor command for ui purposes. I'm sure VS team could have done something just as useful in another way.

查看更多
仙女界的扛把子
7楼-- · 2019-02-11 17:00

My working day starts with opening files in editor and clicking on "Expand All" to hide all regions. After that I can begin to work.

查看更多
登录 后发表回答