阻止 Visual Studio 将 using 指令置于命名空间之外 [英] Stop Visual Studio from putting using directives outside namespace

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

问题描述

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]
代码不需要 using 指令,可以安全删除

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 将 using 指令置于命名空间之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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