在C#中使用verbatim字符串时如何输入双引号

13
我需要打印
a
"b"
c

使用verbatim字符串,我在这里发了另一个有关多行代码模板的问题here

我尝试过以下verbatim字符串:

using System;

class DoFile {

    static void Main(string[] args) {
        string templateString = @"
        {0}
        \\"{1}\\"
        {2}
        ";
        Console.WriteLine(templateString, "a", "b", "c");
    }
}

但是,我遇到了这个错误。

t.cs(8,11): error CS1525: Unexpected symbol `{'
t.cs(9,0): error CS1010: Newline in constant
t.cs(10,0): error CS1010: Newline in constant

"{1}" 也不起作用。

有什么问题吗?

7个回答

22

8
在逐字字符串文字中,您使用""来表示双引号字符。
string line = @"
{0}
""{1}""
{2}";

4
在使用C#的多行字符串文字时,使用@",双引号的正确转义序列变为""而不是\"
    string templateString = @"
    {0}
    ""{1}""
    {2}
    ";

1
在verbatim字符串中,使用""来表示结果中的"

1
在一个@"字符串中,嵌入的双引号应该被转义为""而不是\"。请修改你的代码。
    string templateString = @"
    {0}
    ""{1}""
    {2}
    ";

这样您的问题应该就会消失了。


然后去掉反斜杠。编辑以反映更改。 - Nicholas Carey

0
string templateString = @"        
{0}        
""{1}""
{2}
";

编辑:更新以显示在使用Verbatim时的正确语法。


不正确。OP已经指出这是错误的... - mellamokb
@mellamokb - 谢谢 - 我会先检查我的语法 - Leons

0

使用一个“双倍双引号”来生成输出中的单个双引号。这与旧版VB6处理字符串的方式相同。

@" ""something"" is here"; 

包含一个带引号的字符串。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接