2011-05-13 61 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

您需要将@放在字符串的引号之前,这将使其成为逐字字符串文字,并且仍将使用您使用的所有空白字符。