简体   繁体   English

使用 C# 在 Visual Studio 中命名空间缩进

[英]Namespace indentation in Visual Studio with C#

Visual Studio indents code within namespace. Visual Studio 在命名空间内缩进代码。 This can be avoided when disabling indentation globally, which is not what I want.在全局禁用缩进时可以避免这种情况,这不是我想要的。 In all other cases, the indentation is fine, I simply don't like the fact that all code is one level - this makes it look ugly to me.在所有其他情况下,缩进很好,我只是不喜欢所有代码都是一个级别的事实 - 这让我看起来很难看。

namespace X
{
    public class A
    {}
}

I would prefer it like this:我更喜欢这样:

namespace X
{
public class A
{

}
}

In C++, there's a nice workaround as explained here :在C ++中,有一个很好的解决方法,因为解释在这里

namespace X
{; // the ; after opening brace makes visual studio not indent the class below.

class A
{};

}

But in C#, a namespace cannot directly contain fields so this doesn't work.但是在 C# 中,命名空间不能直接包含字段,因此这不起作用。

How can I get Visual Studio to stop indenting namespaces without disabling indentation globally?如何让 Visual Studio 在不全局禁用缩进的情况下停止缩进命名空间?

Update Visual Studio 2013 behavior C++ has changed更新Visual Studio 2013 行为 C++ 已更改

Tools->Options->C/C++->Formatting->Indentation: [ ] Indent namespace contents 

enables my preferred formatting, while the {;启用我的首选格式,而 {; trick doesn't work anymore.伎俩不再奏效。 But no change for C# that I could find.但是我能找到的 C# 没有变化。

  1. Text Editor → c# → Tabs → Indenting — Set to "Block" 文本编辑器→c#→选项卡→缩进 - 设置为“阻止”
  2. Text Editor → c# → Formatting → General — Turn off every checkbox saying "automatically format..." 文本编辑器→c#→格式化→常规 - 关闭每个复选框,说“自动格式化...”

This question deserves a new answer in 2021. C#10 (shipped with .NET 6 and Visual Studio 2022) introduces File Scoped Namespaces .这个问题值得在 2021 年得到一个新答案。 C#10(随 .NET 6 和 Visual Studio 2022 一起提供)引入了File Scoped Namespaces It allows the following syntax:它允许以下语法:

namespace Hello.World;

class MyClass
{
    public static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

So, we can completely remove indentation added by the namespace declaration.因此,我们可以完全删除命名空间声明添加的缩进。 The old syntax is supported too.旧语法也受支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM