开发者

Ways to make use of 'using' directives in C# less tedious

Good programming practice these days tends to mean splitting your 开发者_如何转开发stuff up into lots of assemblies and namespaces (for example, see S#arp Architecture, MVC, etc.). However a side-effect of that is that you have to stick a whole bunch of 'using ' directives into every class file. You know the sort of thing: Every controller class needs to 'use' the models and viewmodels namespaces, etc., etc.

Are there any techniques for making this easier? For example, is it possible to declare using directives at the namespace level instead of the file level - so that every class in a namespace 'foo' automatically is using namespace 'bar'? Or are there smart ways of setting the default 'usings' that Visual Studio adds, based on the folder you are in? Or other ways of making the adding of 'usings' less tedious?


To make the management of adding 'usings' and removing unnecessary 'usings' less tedious, I recommend trying out JetBrains' ReSharper. It will help recognize when you need to add a missing 'using' and will grey out 'using' statements that are not needed.


As discussed in this question, this is not possible.

When you have long lists of usings, you possibly are also having too much dependencies. It might be an indication that you need to do some refactoring.


Well, you could create your own item template with all the necessary usings and use it when creating new files.


As far as the language goes, there is nothing like what you're after.

The best option you have is to use tools (like some of those in Visual Studio) that allow you to add usings automatically for a selected "unknown symbol", sort usings alphabetically, or strip usings that are no longer required in the current file.


In Visual Studio 2010 you can make adding usings less tedious by typing the type, for example, IEnumerable<int> and if a red box appears (this appears when the using statement is missing) in Visual Studio at the end of the word pressing Ctrl + . whilst the caret is over the type declaration. This should give you a quick menu with an automatic way of adding the missing using statement all from the keyboard.

Alternatively you could define a snippet with your common usings in and remove the unused ones when you have finished with the class using the context menu > organise usings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜