问题
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