使用C#实现代码模板

时间:2011-05-13 18:33:09

标签: c# .net code-generation code-templates

当我需要代码模板时,我可以按如下方式使用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用于生成代码的一部分,而且它真的很长。

4 个答案:

答案 0 :(得分:3)

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

class DoFile {

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

答案 1 :(得分:3)

您需要在第一个引用

之前放置@
templateString = @"
        {0}
        {1}
        {2}
        ";

将其设为 verbatim-string-literal

  

在逐字字符串文字中,   分隔符之间的字符是   逐字解释,唯一的   例外是一个   引号转义序列。特别是,   简单的转义序列和   十六进制和Unicode转义   序列 *未处理* in   逐字字符串文字。 逐字逐句   字符串文字可能跨越多个   线。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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