gpt4 book ai didi

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

转载 作者:bug小助手 更新时间:2023-10-28 10:46:40 25 4
gpt4 key购买 nike

当涉及到 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 中使用大括号:)

关于c# - 使用语句的格式/缩进 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3711373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com