使用C#实现代码模板

当我需要代码模板时,我可以使用Python如下。

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用于生成代码的一部分,而且它确实很长。

你需要在第一个引号之前放置一个@

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

使它成为逐字字符串文字

在逐字字符串文字中,分隔符之间的字符是逐字解释的,唯一的例外是quote-escape-sequence。 特别是, 简单的转义序列和hex和Unicode转义序列 *不会在逐字字符串文字中处理*。 逐字字符串文字可以跨越多行。

这样做(ad @在字符串常量之前):

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

你可以在变量名之前放@来获取多行字符串。

你需要在字符串的引号前放置@,这将使它成为逐字字符串文字,这仍将使用你使用的所有空格。