c#中的逐字符串的多行格式(带@的前缀)

Bra*_*itz 21 .net c# string multiline verbatim-string

我喜欢在c#中使用@"字符串",特别是当我有很多多行文本时.唯一的烦恼是我的代码格式化在做这个时会变成doodie,因为第二个和更多的行被完全推到左边而不是使用我格式精美的代码的缩进.我知道这是设计的,但是有一些选项/ hack方法允许这些行缩进,而不向输出添加实际的制表符/空格吗?

添加示例:

        var MyString = @" this is 
a multi-line string
in c#.";
Run Code Online (Sandbox Code Playgroud)

我的变量声明缩进到"正确"深度,但是字符串中的第二行和更多行被推到左边缘 - 所以代码有点难看.您可以在第2行和第3行的开头添加制表符,但字符串本身将包含这些制表符......有意义吗?

Cym*_*men 11

字符串扩展怎么样?更新:我重读了你的问题,我希望有更好的答案.这也是让我烦恼的事情,并且必须解决它,因为下面是令人沮丧的,但从好的方面来看,它确实有效.

using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    public static class StringExtensions
    {
        public static string StripLeadingWhitespace(this string s)
        {
            Regex r = new Regex(@"^\s+", RegexOptions.Multiline);
            return r.Replace(s, string.Empty);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

一个示例控制台程序:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string x = @"This is a test
                of the emergency
                broadcasting system.";

            Console.WriteLine(x);

            Console.WriteLine();
            Console.WriteLine("---");
            Console.WriteLine();

            Console.WriteLine(x.StripLeadingWhitespace());

            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并输出:

This is a test
                of the emergency
                broadcasting system.

---

This is a test
of the emergency
broadcasting system.
Run Code Online (Sandbox Code Playgroud)

如果您决定采用这条路线,可以使用它更简洁的方法:

string x = @"This is a test
    of the emergency
    broadcasting system.".StripLeadingWhitespace();
// consider renaming extension to say TrimIndent() or similar if used this way
Run Code Online (Sandbox Code Playgroud)


Bat*_*nit 6

在 C# 11 中,您现在可以使用原始字符串文字

var MyString = """
    this is 
    a multi-line string
    in c#.
    """;
Run Code Online (Sandbox Code Playgroud)

输出是:

this is
a multi-line string
in c#.
Run Code Online (Sandbox Code Playgroud)

它还与字符串插值结合:

var variable = 24.3;
var myString = $"""
    this is 
    a multi-line string
    in c# with a {variable}.
    """;
Run Code Online (Sandbox Code Playgroud)


Dig*_*nce 5

Cymen已经给出了正确的解决方案.我使用类似于Scala的stripMargin()方法的方法.这是我的扩展方法的样子:

public static string StripMargin(this string s)
{
    return Regex.Replace(s, @"[ \t]+\|", string.Empty);
}
Run Code Online (Sandbox Code Playgroud)

用法:

var mystring = @"
        |SELECT 
        |    *
        |FROM
        |    SomeTable
        |WHERE
        |    SomeColumn IS NOT NULL"
    .StripMargin();
Run Code Online (Sandbox Code Playgroud)

结果:

SELECT 
    *
FROM
    SomeTable
WHERE
    SomeColumn IS NOT NULL
Run Code Online (Sandbox Code Playgroud)