2011-05-13 153 views
10

我需要打印把」在逐字字符串與C#

a 
"b" 
c 

與vebatim串,我提出了關於多行代碼模板here另一個問題

我試圖與逐字字符串如下:

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}\"也不工作。

怎麼了?

+0

可能重複[我可以在逐字串字面值中使用雙引號嗎?](http://stackoverflow.com/questions/1928909/can-i-escape-a-double-quote-in-a-verbatim -string-literal) – Ash 2017-03-22 12:28:06

回答

3

在C#中使用帶@"的多行字符串文字時,雙引號的正確轉義序列變爲""而不是\"

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

在逐字字符串文字中,對於雙引號字符使用""

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

在逐字字符串,請使用""在結果"

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

編輯:更新到使用逐字逐句顯示正確的語法。

+0

不正確。 OP已經注意到這是錯誤的... – mellamokb 2011-05-13 18:49:53

+0

@mellamokb - 謝謝 - 我將首先檢查我的語法 – Leons 2011-05-13 19:00:19

0

在一@"字符串,嵌入式雙引號轉義爲"",而不是\"。將您的代碼更改爲

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

並且您的問題應該消失。

+0

然後丟失反斜槓。編輯以反映變化。 – 2011-05-13 18:51:15

0

使用「double double」引號在輸出中產生一個雙引號。這與舊式VB6處理字符串的方式相同。

@" ""something"" is here"; 

包含一個帶有引號的字符串。