2011-05-13 63 views
3

當我需要代碼模板時,我可以像下面這樣使用Python。用C#代碼模板實現#

templateString = """ 
%s 
%s 
%s 
""" 

print templateString % ("a","b","c") 

如何用C#實現等價物?

我試圖

using System; 

class DoFile { 

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

但我得到

dogen.cs(86,0): error CS1010: Newline in constant 
dogen.cs(87,0): error CS1010: Newline in constant 
dogen.cs(88,0): error CS1010: Newline in constant 

當然templateString = "{0}\n{1}\n{2}\n";的作品,但我需要使用多行模板,因爲templateString是用於生成代碼的一部分,它是真正長。 (字符串常量前廣告@)

回答

3

你需要放置一個@第一報價之前

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

使其成爲verbatim-string-literal

In逐字字符串文字, 分隔符之間的字符是 逐字解釋,唯一的 例外是一個 quote-escape-sequence。特別是, 簡單轉義序列和 十六進制和Unicode轉義 序列 *不處理*在 逐字字符串文字。 逐字 字符串文字可能會跨越多個 行。

3

而是執行此操作:

class DoFile { 

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

你可以在變量名前加@來獲得多行字符串。

0

您需要將@放在字符串的引號之前,這將使其成爲逐字字符串文字,並且仍將使用您使用的所有空白字符。