简体   繁体   English

在 Visual Studio 中格式化文档以插入大括号?

[英]Format document in Visual Studio to insert braces?

Is there a way to "Format document" in Visual Studio to insert braces around single-statement blocks for C# code?有没有办法在 Visual Studio 中“格式化文档”以在 C# 代码的单语句块周围插入大括号? For example this:例如这个:

if (x)
    y();

... would become something like: ...会变成这样:

if (x) { y(); }

The auto formatting seems to deal with indentation but not this brace insertion.自动格式化似乎处理缩进,但不是这个括号插入。 Is there a way to do it?有没有办法做到这一点?

In case you have resharper you can configure it to force braces depending on your criteria.如果您有resharper,您可以将其配置为根据您的标准强制使用大括号。 Than in the existing code press ctrl alt shift f , it will format whole file.比在现有代码中按ctrl alt shift f ,它将格式化整个文件。 Or select just part of the code, in this case resharper will format just selection或者只选择部分代码,在这种情况下,resharper 将格式化只选择

PS ctrl alt f opens clean up dialog. PS ctrl alt f打开清理对话框。 You can configure cleanup options.您可以配置清理选项。

在此处输入图片说明

Actually, there seems to be something built-in to Visual Studio to do this.实际上,Visual Studio 似乎内置了一些东西来做到这一点。

If you go to Tools -> Options -> Text Editor -> C# -> Formatting -> New Lines and make sure that you have Place open braces on new lines for control block checked.如果您转到Tools -> Options -> Text Editor -> C# -> Formatting -> New Lines ,并确保已选中Place open braces on new lines for control block

Then, go to your document and use the key combination CTRL K D , this should reformat your document and add the curly braces.然后,转到您的文档并使用组合键CTRL K D ,这应该重新格式化您的文档并添加花括号。

I gave a vote to Gimly's answer as it is pretty much correct.我对 Gimly 的回答投了票,因为它非常正确。 These things change over time of course.这些事情当然会随着时间而改变。 I would have added a comment but I wanted to paste in some images.我会添加评论,但我想粘贴一些图像。 Location of settings in VS2019 is at: VS2019 中设置的位置在: 在此处输入图像描述

Uncheck the appropriate check boxes and select OK.取消选中相应的复选框并选择确定。

The shortcut key did not work, which is a shame because, I love them!快捷键不起作用,这是一种耻辱,因为,我爱他们! This documentation suggests that you use CTRL-K, CTRL-E or, you use the broom icon:文档建议您使用 CTRL-K、CTRL-E 或使用扫帚图标:

在此处输入图像描述 . .

Neither option worked for me perhaps because, that is not the intention, given the list of options.这两个选项都不适合我,也许是因为考虑到选项列表,这不是本意。 However, if you mark and cut all your code and then, paste the code back into the file, the new standard is adopted.但是,如果您标记并剪切所有代码,然后将代码粘贴回文件中,则采用新标准。

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

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