使用C#实现代码模板

3
当我需要代码模板时,我可以使用以下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个回答

3

请改用以下方式(在字符串常量前添加 @):

class DoFile {

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

3

第一个引号前面加上@

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

将其变为逐字字符串字面量

在逐字字符串字面量中,定界符之间的字符被逐字解释,唯一的例外是引号转义序列。特别地,简单转义序列和十六进制和Unicode转义序列 *不会* 在逐字字符串字面量中被处理。 逐字字符串字面量可以跨越多行。


0

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


0
你需要在字符串的引号前加上@符号,这将使其成为逐字字符串文字,并且仍将使用你所使用的所有空格。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接