在 Visual Studio Code 中自动格式化 C# 代码

问题描述:

我在 Visual Studio Code 编辑器中启用了最新的 C# 扩展.而不是在保存时格式化代码或通过应用组合键 Ctrl + KCtrl + FAlt + Shift + F,我需要在按下 Enter 键的同时格式化当前代码行.此功能已在 Visual Studio 中可用,但默认情况下未在 Visual Studio Code 中找到.

I have enabled the latest C# extension in my Visual Studio Code editor. Instead of formatting the code while saving or by applying the key combination Ctrl + K, Ctrl + F or Alt + Shift + F, I need to format the current line of code while hitting the Enter key. This feature is already available in Visual Studio, but not found in Visual Studio Code by default.

这是我需要实现的示例代码输出:

This is the sample code output I need to achieve:

Go to menu FilePreferencesKeyboard Shortcut (Ctrl + K, Ctrl + S)

Go to menu FilePreferencesKeyboard Shortcut (Ctrl + K, Ctrl + S)

点击 keybindings.json 链接:

Enter 键输入以下绑定.此绑定将覆盖当前用户的默认设置.

Enter the below binding for the Enter key. This binding will overwrite the defaults for current user.

{
  "key": "enter",
  "command": "editor.action.formatDocument",
  "when": "editorHasSelection"
}

另一种替代解决方案是使用宏扩展a> - 对 Visual Studio Code 的自定义宏支持,因此您将能够在一个键绑定中执行多个命令.

Another alternative solution is to use macros extension - a custom macros support for Visual Studio Code, so you will be able to do more than one command in one key binding.

用户设置添加宏:

"macros": {
    "formatWithEnter": [
        "editor.action.insertLineAfter",
        "editor.action.formatDocument"
    ]
}

以及以下键绑定到 keybindings.json:

{
    "key": "enter",
    "command": "macros.formatWithEnter"
}