阻止Visual Studio在命名空间外使用指令 [英] Stop Visual Studio from putting using directives outside namespace

查看:78
本文介绍了阻止Visual Studio在命名空间外使用指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Visual Studio(或Resharper)中是否有一个设置,可让您指定默认的命名空间以及它们的作用域?

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?

例如,MVC项目的默认值为

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
    {
    }
}

但是Resharper和Stylecop抱怨:

but Resharper and Stylecop complain:

所有using指令必须放置在名称空间内.[StyleCop规则:SA1200]
代码不需要使用指令,可以安全地将其删除

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
    {
    }
}

推荐答案

通常,我不认为在类的顶部包含 using 陈述式有什么害处.实际上,我发现将它们包含在其中比较容易,因此,是否要遵守该规则取决于您.

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.

但是,如果您这样做,则所有文件模板都可用并且可以进行编辑.参见答案如何我要为新的C#类/界面编辑Visual Studio模板吗?详细说明它们在每个Visual Studio版本上的位置.

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!

这篇关于阻止Visual Studio在命名空间外使用指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆