如何在Visual Studio 2015中粘贴时保留格式?

时间:2016-01-28 19:26:05

标签: c# visual-studio

我的函数部分有一个switch case,我需要重新排序一些案例以便更好地读取代码。

所以现在的代码看起来像这样:

switch(parameter) {
      case "foo" : {DoSomething; DoSomething; DoSomething; DoSomething; break }
      case "bar" : {DoSomething; DoSomething; DoSomething; DoSomething; break }  
      ....
      case "alpha" : {DoSomething; DoSomething; DoSomething; DoSomething; break }
      case "beta" :  {DoSomething; DoSomething; DoSomething; DoSomething; break }
 }

所以我在这个switch语句里面有几个案例,我需要重新排序它们中的大多数。并且在重新排序时,例如,如果我想将案例foo和案例栏放在案例alpha和beta之下。一个简单的Ctrl+cCtrl+v给我一个这样的输出:

switch(parameter) {
      case "alpha" : {DoSomething; DoSomething; DoSomething; DoSomething; break }
      case "beta" :  {DoSomething; DoSomething; DoSomething; DoSomething; break }
      ......
      case "foo" : {DoSomething; 
                    DoSomething; 
                    DoSomething; 
                    DoSomething; 
                    break }
      case "bar" : {DoSomething;
                    DoSomething; 
                    DoSomething;
                    DoSomething; 
                    break }  
 }

多次重新排列此文本是一项繁琐的任务。有没有一种方法可以复制一行,因为它在代码的其他部分?

例如,我希望整个文本保持在以前的单行中,

  case "foo" : {DoSomething; DoSomething; DoSomething; DoSomething; break }
  case "bar" : {DoSomething; DoSomething; DoSomething; DoSomething; break }  

6 个答案:

答案 0 :(得分:37)

您正在体验"功能" Visual Studio自动格式化某些操作的代码(上的已完成语句; }上的已完成块粘贴。幸运的是,这些可以通过以下设置页面更改首选项(它们是特定于语言的):

VS 2015

Tools > Options > Text Editor > C# > Formatting

然后暂时取消选中粘贴时自动格式化选项。

General C# formatting options

VS 2017/2019

在Visual Studio 2017和2019中,"格式化"选项在新的" Code Style"下面移动。菜单并添加了一些额外的设置:

enter image description here

答案 1 :(得分:6)

这可能听起来很愚蠢,但是粘贴和重新格式化功能在Visual Studio中的工作方式是Visual Studio首先粘贴,然后以不同的步骤格式化文本。

如果您不想禁用"自动格式化粘贴"功能,试试这个:

  1. 正常粘贴文本(VS将格式化文本,但挂起)
  2. 多次撤消(Ctrl + Z),直到所有格式化步骤都已恢复

答案 2 :(得分:3)

由于这个问题通常与重新排序有关,因此也可能有所帮助。

轻松重新排序代码:选择要移动的代码,然后使用 Alt + UpArrow Alt + DownArrow 向上或向下移动选择。对于缩进选择,使用 Tab Shift + Tab 来移动缩进。

答案 3 :(得分:3)

这个答案有点晚了但如果有人仍然遇到问题,请尝试使用不带格式化快捷方式的粘贴( CTRL + Shift + V )。

它适用于Visual Studio 2017。

答案 4 :(得分:0)

如果您使用的是Visual Assist,请确保还禁用Visual Assist options -> Editor -> Format after paste中的选项,因为Visual Assist具有自动粘贴后自动格式化的功能。

答案 5 :(得分:-2)

在粘贴之前关闭所有自动格式化。