C# 字符串中‘$‘和‘@‘的使用

  1. 使用$符号:

    在C#中,当你想要在字符串中嵌入变量或者表达式,并且想要这些嵌入的内容自动计算其值,可以使用插值字符串(Interpolated Strings)。这是通过在字符串前加上$符号来实现的。

    例如:

    int number = 10;

    string message = $"The number is {number}";

    Console.WriteLine(message); // 输出: The number is 10

    在这个例子中,{number}会被其值10所替换。

  2. 使用@符号:

    当你需要在字符串中包含大量的换行符,或者在字符串中直接使用反斜杠\而不会将其解释为转义字符时,可以使用逐字字符串(Verbatim String Literals)。这是通过在字符串前加上@符号来实现的。

    例如:

    string path = @"C:\Users\Public\Documents\Report.txt";

    string multiLineString = @"This is the first line.

    This is the second line.";

    Console.WriteLine(path); // 输出: C:\Users\Public\Documents\Report.txt

    Console.WriteLine(multiLineString); // 输出两行文本,每行一个字符串

    在第一个例子中,反斜杠被直接解释为普通字符,不会被视为转义字符。在第二个例子中,字符串可以跨多行,而不需要使用+来连接多行字符串。

你可能感兴趣的:(字符串嵌入变量)