我该如何在类模板中使用文件作用域命名空间声明?

16

C# 10引入了文件范围命名空间,我希望在Visual Studio的类模板中使用它。我已经将“Class”模板文件更新为以下内容:

namespace $rootnamespace$;
class $safeitemrootname$
{
    //I put this comment here to make sure it's using the right file
}

但是当我创建一个新的空类时,我会得到这个自动生成的代码:

namespace ProjectName
{
    internal class Class1
    {
        //I put this comment here to make sure it's using the right file
    }
}

我需要做什么才能让自动生成的空类代码看起来像这样?

namespace ProjectName;  
internal class Class1
{

}

供参考,我正在使用Visual Studio 2022 Professional,并且我的项目正在使用C#10和.NET 6。

我正在修改的类模板文件位置是:C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.cs


The VS模板是开源的,你可以尝试找到其中一个新的并进行比较。 - TheGeneral
@TheGeneral 你会在哪里寻找它们? - Nigel
2个回答

22

你需要设置项目的editorconfig以更倾向于使用文件范围的命名空间。

  1. 右键点击你的项目。选择“添加” → “新建项”

  2. 选择“editorConfig 文件 (.NET)”

  3. 双击新的editorconfig文件。在“代码样式”选项卡中将“命名空间声明”设置为“文件范围”

enter image description here

现在代码模板将按预期工作。


2
不仅可以将“.editorconfig”文件添加到您的项目中,还可以将其添加到解决方案中,并使其适用于解决方案中的所有项目。 - Uwe Keim
@UweKeim 在我的测试中,这还是相当有限的。 - Mr. Boy

4

嗨,尼尔斯,感谢您的回答。我能够使用那个线程找到答案。我将撰写一篇更详细、更实时的答案,供VS2022使用。 - Nigel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接