c# - 使用语句的格式/缩进 (C#)

当涉及到 C# 中的 using 语句(不要与导入命名空间的 using directives 混淆)时,Visual Studio 不会如果没有使用大括号,则缩进后面的单行代码。这是典型的“嵌套”使用语句,如 this SO question 所示。 .

我发现 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())

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

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

一如既往地感谢所有回答问题的人,即使是这些次要的编程细节也能提供洞察力和经验。

最佳答案

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

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

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

https://stackoverflow.com/questions/3711373/

相关文章:

java - 如何在 Java 中设置尊重用户操作系统设置的日期和时间格式

ruby - 将字符串日期格式从 "17-Nov-2011"转换为 "11/17/11"

android - 阻止 Android Studio 包装方法和构造函数

reporting-services - 格式化电话号码并在返回为空时隐藏#ERROR SSRS

c# - Visual Studio 改变了 Ctrl-K-D 的工作方式

r - 如何将具有混合日期格式的变量转换为一种格式?

java - 如何在 Java 中使用前导空格格式化数字

sql - 需要一个工具来自动缩进和格式化 SQL Server 存储过程

html - Aptana 3 中的代码格式化

date - 谷歌书签导出日期格式?