使逐字字符串文字自动缩进以保持与附近代码保持一致

RSW*_*RSW 11 c# string auto-indent autoformatting visual-studio-2013

在C#中,我经常使用逐字字符串文字(例如@"Arrr!")来跨越多行来断开长字符串,同时保留布局.例如,我使用它来分解内联SQL,如下所示:

var sqlString = @" 
    SELECT 
        Column1
        , ...
    FROM
        Table1 INNER JOIN ...
    WHERE 
        Column2 = @Value2
        , ...
    ";
Run Code Online (Sandbox Code Playgroud)

...或者打破这样的正则表达式模式:

var regexPattern = @"
    (?<state>\w+)[.]?                       (?#*** Matches state {optionally having a period at the end} ***)
    (\s+|,|,\s+|\s*\u2022\s*)               (?#*** Matches space between state and zip {can include a comma or bullet point} ***)
    (?<zip>(\d{5}-\d{4}\b|\d{5}(?![\w-])))  (?#*** Matches zip code ***)
    ";
Run Code Online (Sandbox Code Playgroud)

 

但是,如果此代码稍后自动缩进,则逐字字符串文字不会自动缩进.当它上方和下方的代码行向右移动时,它会被遗忘.结果是它与其他一切都不一致.例如:

之前:

verbatim = @"               ___
    I likes my                 |
    strings purty              | indented the way I like!
    ";                      ___|
fooBar = "nomnom";
Run Code Online (Sandbox Code Playgroud)

围绕"IF"声明后:

if (true)
{
    if (maybe)
    {
        verbatim = @"       ___
    I likes my                 |
    strings purty              | no longer indented the way I like =(
    ";                      ___|
        fooBar = "nomnom";
    }
}
Run Code Online (Sandbox Code Playgroud)

 

我如何使Visual Studio自动缩进我的逐字字符串文字的行,就像它与其他代码行一样?

 

笔记

  • 我不想在每一行上使用普通字符串并将它们连接在一起就像这样(这是我过去常常这样做但我发现自由格式的逐字字符串文字更容易阅读和修改):

    notverbatim = 
        "Alas! " 
        + "This doth " 
        + "make me sad =( " 
        ; 
    
    Run Code Online (Sandbox Code Playgroud)
  • 因为通过在每行的左边添加新的空格来缩进多行逐字字符串文字"增长字符串",我意识到有一些逐字字符串文字,这是不可取的.如果在Visual Studio中全局设置此行为会通过缩进其他不应该使用的逐字字符串文字而导致意外后果,是否有办法在代码中标记单个逐字字符串文字,以便它们自动缩进而其他所有字符串文字不?

小智 1

通过更改“缩进”设置,我能够让 VS2017 以这种方式运行。我更改的是Tools -> Options -> Text Editor -> C# -> Tabs。该屏幕的顶部是标题为“缩进”的部分。将其从“智能”更改为“阻止”会产生与 VS2010 开箱即用的工作方式类似的行为(至少对我来说)。

我刚刚进行了此更改,因此我不确定对其他类型缩进的全部影响,但对于逐字字符串来说,它似乎有效。