禁用Visual Studio中特定代码块的代码格式

时间:2019-02-24 06:27:19

标签: c# visual-studio code-formatting

我想知道是否有办法 Visual Studio 2017 (C#7)中的特定代码块禁用代码格式

我有这种方法:

public CarViewModel(ICarsRepo carsRepo)
{
    ...

    Manufacturers = ToSelectList<Manufacturer>();
    Categories = ToSelectList<Category>();
    States = ToSelectList<State>();
}

我想这样格式化:

public CarViewModel(ICarsRepo carsRepo)
{
    ...

    Manufacturers   = ToSelectList<Manufacturer>();
    Categories      = ToSelectList<Category>();
    States          = ToSelectList<State>();
}

但是当我按下 Ctrl K + Ctrl D 时,它又回到了以前。

region灵感

我想包装一些特定的代码块,例如region

public CarViewModel(ICarsRepo carsRepo)
{
    ...

    #region disable_format

    Manufacturers   = ToSelectList<Manufacturer>();
    Categories      = ToSelectList<Category>();
    States          = ToSelectList<State>();

    #endregion
}

pragma灵感

或者不一定像本代码段中那样使用region,也许是pragma

            var parameter = 0;
            var sqlCommand = $"{parameter}";
#pragma warning disable EF1000 // Possible SQL injection vulnerability.
            this.Database.ExecuteSqlCommand(sqlCommand);
#pragma warning restore EF1000 // Possible SQL injection vulnerability.

这是一种审美上的偏爱,大多数开发人员可能不会分享,但是我有时会在我的代码中很喜欢。

3 个答案:

答案 0 :(得分:2)

  • Visual Studio reference

    • 要禁用格式设置:exec()
    • 要启用格式设置:#pragma warning disable format
    #pragma warning restore format
  • 车手doc

    • 要禁用格式设置: switch (number) { #pragma warning disable format case 1: cardinal = "one"; animal = "monkey"; break; case 2: cardinal = "two"; animal = "horse"; break; case 3: cardinal = "three"; animal = "pig"; break; case 4: cardinal = "four"; animal = "chicken"; break; #pragma warning restore format }
    • 要启用格式设置:// @formatter:off
    // @formatter:on
  • 组合

        switch (number) {
            // @formatter:off
            case 1:    cardinal = "one";     animal = "monkey";     break;
            case 2:    cardinal = "two";     animal = "horse";      break;
            case 3:    cardinal = "three";   animal = "pig";        break;
            case 4:    cardinal = "four";    animal = "chicken";    break;
            // @formatter:on
        }
    

答案 1 :(得分:1)

这不仅会禁用一部分格式,还会阻止Visual Studio格式化您的任何声明语句。

enter image description here

答案 2 :(得分:0)

以下符合您的需求。不仅C#,还支持任何语言。

Manufacturers/**/= ToSelectList<Manufacturer>();
Categories/*   */= ToSelectList<Category>();
States/*       */= ToSelectList<State>();