13

对于C# 中的语句(不要与导入命名空间的指令using混淆),如果没有使用大括号,Visual Studio 不会缩进后面的单行代码。这是典型的“嵌套”使用语句,如这个 SO question中所示。using

我发现后面using的语句没有缩进令人困惑,这与if语句的格式不同:

// non-indented using statement
using (var myResource = new SomeIDisposableResource())
myResource.Indent(false);

// indented if statement
if (something == true)
    IndentMe();

有什么理由缩进,还是只是偏好?

// indented using statement, but not the default VS formatting
using (var myResource = new SomeIDisposableResource())
    myResource.Indent();

编辑:

进一步的测试表明我对某些 VS 格式化行为是不正确的。如果您键入 using 语句:

using (var myResource = SomeIDisposableResource())

...然后按 Enter,光标将与using. 如果下一行也是 using 语句,则继续对齐。如果不是,VS 将在完成时缩进它。因此,我最初的问题有些无效,因为我的第一个示例实际上无法实现,除非您覆盖默认格式或使用不这样做的 IDE。

尽管如此,值得知道的using是,最好将多个语句视为一个块,因为它们在技术上是。仅当语句是using没有大括号的连续语句时,没有缩进才适用;随着人们习惯了它,它们看起来不再那么不寻常了。

一如既往地感谢所有在这些次要编程细节方面提供洞察力和经验的人。

4

5 回答 5

25

正如其他人所说,始终使用大括号。然而,有一个习语有点违背这一点使用“非缩进”:

using (Resource1 res1 = new Resource1())
using (Resource2 res2 = new Resource2())
using (Resource3 res3 = new Resource3())
{
    // Do stuff with res1, res2 and res3
}

但我总是在最里面的块上使用大括号:)

于 2010-09-14T17:36:47.617 回答
13

这是偏好。我总是缩进,并将必要的项目放在括号中

using(var t = new t())
{
   t.Foo();
}
于 2010-09-14T17:31:37.340 回答
5

简单修复:始终使用显式块,即使是单行。然后 Visual Studio 将正确缩进,作为奖励,您的代码将更易于维护!

于 2010-09-14T17:32:23.813 回答
0

就像我的 C 老师在 10 多年前告诉我的那样:总是、总是、总是使用牙套。很有可能有人会出现(甚至可能是你)并输入另一行代码,然后想知道为什么它的行为不正确。

于 2010-09-14T18:12:31.943 回答
0

当我错了时,我喜欢被否决,所以我将对此做出回答......

这是我将如何格式化它:

using (Resource1 res1 = new Resource1())
using (Resource2 res2 = new Resource2())
using (Resource3 res3 = new Resource3())
  DoStuffWithResources(res1, res2, res3);

如果我DoStuffWithResources要用多个语句替换,我会使用大括号。但是,我的编辑器阻止我犯以下错误:

using (Resource1 res1 = new Resource1())
using (Resource2 res2 = new Resource2())
using (Resource3 res3 = new Resource3())
  DoStuffWithResources(res1, res2, res3);
  DoOtherStuffWithResources(res1, res2, res3);

当我尝试输入上述内容时,我立即得到:

using (Resource1 res1 = new Resource1())
using (Resource2 res2 = new Resource2())
using (Resource3 res3 = new Resource3())
  DoStuffWithResources(res1, res2, res3);
DoOtherStuffWithResources(res1, res2, res3);

专业提示:反对票不是反对意见,所以如果你没有反对意见,你就不应该投票。

于 2010-09-14T18:33:04.970 回答