我已成功使用StringTemplate 4在Visual Studio中进行了一些代码生成。我已经安装了StringTemplate和ANTLR的扩展,它们确实很棒。

在测试中,我可以弄清楚如何使用* .st4(StringTemplate)文件,但是如何使用* .stg(StringTemplateGroup)文件使我无所适从。它是可以嵌入到另一个StringTemplate中的定义的集合吗?如果是这样,那么从* .stg而不是* .st4生成的代码将是什么样?

最佳答案

StringTemplate组文件是存储在单个文件中的模板的集合。 GitHub上的ANTLR项目包含许多示例。例如Java.stg包含ANTLR 4的Java目标的所有代码生成模板。

您可以在StringTemplate C#项目本身的StringTemplateTests.cs文件中找到几个在C#中使用StringTemplate 3的示例。它不是最友好的文档,但确实包含涵盖了许多ST3功能的示例。这是使用StringTemplateGroup的一个示例:

string templates =
        "group dork;" + newline +
        "" + newline +
        "test(name) ::= <<" +
        "<(name)()>" + newline +
        ">>" + newline +
        "first() ::= \"the first\"" + newline +
        "second() ::= \"the second\"" + newline
        ;
StringTemplateGroup group =
        new StringTemplateGroup( new StringReader( templates ) );
StringTemplate f = group.GetInstanceOf( "test" );
f.SetAttribute( "name", "first" );
string expecting = "the first";
Assert.AreEqual( expecting, f.ToString() );


因此更容易阅读,该测试中的模板组文件代码看起来像这样,没有转义符。

group dork;

test(name) ::= <<<(name)()>
>>
first() ::= "the first"
second() ::= "the second"

关于c# - StringTemplate与StringTemplateGroup,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16472125/

10-09 05:36