Visual Studio 中的暂存代码行

Visual Studio 2022 版本 17.3 及更高版本中已提供行暂存支持(也称为交互式暂存)。 行暂存允许直接从代码编辑器暂存文件中的更改区块。 如果要跨不同的提交拆分更改,行暂存也很有用。

Screenshot of an example of line-staging support in Visual Studio 2022.

从 Visual Studio 2022 版本 17.6 开始,使用悬停选项还可以逐行取消暂存更改。

Screenshot of an example of how to unstage changes in Visual Studio 2022.

颜色边距支持

关于行暂存支持,你可能会注意到的第一件事是编辑器如何在滚动条和边距上可视化 Git 更改。

Screenshot of the color margins in the Visual Studio 2022 editor.

通过颜色和批注,可以轻松地区分已添加、删除或修改的已保存和未保存的更改。

Screenshot of differentiated and annotated color margin examples in Visual Studio 2022.

提示

可以更改 Visual Studio 显示的颜色,以帮助管理更改。 转到“工具”>”选项”>“环境”>“字体和颜色”,然后从以下选项中进行选择:

  • 跟踪源代码管理下文档中的新增项
  • 跟踪源代码管理下文档中的删除项
  • 跟踪源代码管理下文档中的修改项

Screenshot of the Options dialog box where you can change the colors Visual Studio uses for source control.

速览差异支持

颜色边距是交互式的。 选择颜色边距时,Visual Studio 会打开“速览差异”用户界面 (UI),你可以在其中查看编辑器中的更改,而无需切换上下文。 “速览差异”UI 汇总了添加和删除的行数,并使你能够使用向上和向下箭头轻松地在更改之间导航。

Screenshot of the Peek Difference user interface in Visual Studio as it relates to source control.

右键单击包含更改的行时,还可以访问“速览差异”。 此时会显示一个上下文菜单,可在其中选择“速览差异”。 或者,可以使用 Alt+F8 键盘快捷方式。

Screenshot of the right-click context menu in Visual Studio where you can select Peek Difference.

注意

如果更喜欢内联差异视图,可以使用“差异”编辑器右上角的“设置”控件切换到“内联模式”。

Screenshot of the Diff options available from the gear icon, where you can select the 'Inline mode' option.

提示

可以使用“工具”>“选项”>“文本编辑器”>“高级””中的“单击以速览边距”选项修改 Visual Studio 与“速览差异”UI 中的代码更改的交互方式。 Screenshot of the 'Click to peek in margin' setting.例如,可以将默认的“单击”设置更改为“双击”,也可以选择“无”以关闭“速览差异”UI。

暂存代码块

可以使用“速览差异”用户界面 (UI) 暂存任何代码块。 为此,请将鼠标悬停在要暂存的更改上,然后选择“暂存更改”。 或者,如果要暂存对文档所做的所有更改,请使用全局“暂存”按钮。

Screenshot of the Stage Change option in Visual Studio 2022.

如果更喜欢全屏差异视图,可以切换到“差异”编辑器。 操作方法如下:选择“速览差异”UI右上角的“提升到文档”按钮 。 或者,可以使用 Ctrl+Alt+Home 键盘快捷方式。 “速览差异”UI 提供的所有功能也可在“差异”编辑器中使用。

Screenshot of the Stage Change difference view in Visual Studio 2022.

提交暂存更改

通过查看和暂存要包括的更改来准备提交后,可以使用“Git 更改”窗口创建提交。 接下来,输入提交消息,然后选择“提交暂存”。

Screenshot of the Git Changes dialog in Visual Studio 2022.