首页 文章

阻止Visual Studio在命名空间外部使用指令

提问于
浏览
17

Visual Studio(或Resharper)中是否有一个设置允许您指定哪些命名空间应该是默认的以及它们放在哪个范围内?

例如,MVC项目的默认值是

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

namespace Namespace
{
    public class Class1
    {
    }
}

但Resharper和Stylecop抱怨说:

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

有没有办法简单地制作默认值:

namespace Namespace
{
    public class Class1
    {
    }
}

3 回答

  • 9

    一般来说,我不会在你 class 的最高层包括 using 州政府的任何伤害 . 我实际上发现将它们包含在那里更容易,因此您是否要尊重该规则取决于您 .

    但是,如果您这样做,则所有文件模板都可用并且可以编辑 . 请参阅答案How do I edit the Visual Studio templates for new C# class/interface?以详细说明它们在每个Visual Studio版本上的位置 .

    一旦你在那里你可以改变布局,所以例如基本类看起来像:

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

    您可以将此更改为以下或类似:

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

    可能会有相当多的文件要改变!

  • 0

    您可以在Re-sharper中进行设置 .

    重新锐化>选项> C#>命名空间导入>将使用指令添加到最深的范围 .

  • 16

    VS 2015和2017还有一个Visual Studio扩展,它在事后修复了 using 声明 . 它还有一些用于对特定声明进行分组的配置选项(如 System.*

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

    enter image description here

相关问题