Stop Visual Studio from putting using directives outside namespace

半世苍凉 提交于 2021-02-06 14:51:06

问题


Is there a setting in Visual Studio (or Resharper) that allows you to specify what namespaces should be default and which scope they are put in?

The default for an MVC project for example is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Namespace
{
    public class Class1
    {
    }
}

but Resharper and Stylecop complain:

All using directives must be placed inside of the namespace. [StyleCop Rule: SA1200]
Using directive is not required by the code and can be safely removed

Is there a way to make the default simply:

namespace Namespace
{
    public class Class1
    {
    }
}

回答1:


Generally I don't believe there's any harm in including using statementents at the top of your class. I actually find it easier to include them there, so it's up to you whether you want to respect that rule.

If you do however, all of the file templates are available and can be edited. See the answer How do I edit the Visual Studio templates for new C# class/interface? to detail where they live on each Visual Studio version.

Once you're there you can change the layout, so for example a basic class looks like:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;
$if$ ($targetframeworkversion$ >= 4.5)using System.Threading.Tasks;
$endif$
namespace $rootnamespace$
{
    class $safeitemrootname$
    {
    }
}

You could change this to the following or similar:

namespace $rootnamespace$
{
    using System;
    using System.Collections.Generic;
    $if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
    $endif$using System.Text;
    $if$ ($targetframeworkversion$ >= 4.5)using System.Threading.Tasks;
    $endif$

    class $safeitemrootname$
    {
    }
}

There may be quite a few files to change though!




回答2:


You can set this in Re-sharper.

Re-sharper > Options > C# > Namespace Imports > Add using directive to the deepest scope.


Update: As of VS2015 and Resharper10, this has moved. It is now under:

Code Editing > C# > Code Style > Reference qualification > Add 'using' directive to deepest scope




回答3:


In Resharper 2020 it's under Code Editing > C# > Syntax Style > Add 'using' directive to deepest scope.




回答4:


There's also a Visual Studio extension for VS 2015 and 2017 that fixes using declarations after the fact. It also has some configuration options for grouping particular declarations (like System.*)

https://marketplace.visualstudio.com/items?itemName=everfor88.UsingDirectiveFormatter



来源:https://stackoverflow.com/questions/26629264/stop-visual-studio-from-putting-using-directives-outside-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!