c# - 将列表值传递给 t4 模板

标签 c# t4

我使用了代码 here将参数传递给模板文件。

List<string> TopicList = new List<string>();
TopicList.Add("one");
TopicList.Add("two");
TopicList.Add("three");
TopicList.Add("four");
TopicList.Add("five");
PreTextTemplate1 t = new PreTextTemplate1();
t.Session = new Microsoft.VisualStudio.TextTemplating.TextTemplatingSession();
t.Session["TimesToRepeat"] = 5;
foreach (string s in TopicList)
{
    t.Session["Name"] = s;
}
t.Initialize();
string resultText = t.TransformText();

但每次,我得到的只是主题列表中的最后一个值(“五”)。

<#@ template language="C#" #>
<#@ parameter type="System.Int32" name="TimesToRepeat" #>
<#@ parameter type="System.String" name="Name" #>

<# for (int i = 0; i < TimesToRepeat; i++) { #>
Line <#= Name #>
<# } #>

Actual Output:Line five
              Line five
              Line five
              Line five
              Line five

Expected Output: Line one
                 Line two
                 Line three
                 Line four
                 Line five

如何才能生成模板中主题列表中的每个值? 就像预期的输出。

很抱歉这个问题的英语和格式很糟糕。

最佳答案

我没有使用过 TextTemplating,所以让我先声明一下我在这里可能不正确。就我通过观察它所看到的而言,您在模板中错误地定义了 Name 。尝试以下操作:

<#@ template language="C#" #>
<#@ parameter type="System.Int32" name="TimesToRepeat" #>
<#@ parameter type="System.Collections.Generic.List<System.String>" name="Names" #>

<# for (int i = 0; i < TimesToRepeat; i++) { #>
Line <#= Names[i] #>
<# } #>

您也可以删除 TimesToRepeat 并改用 foreach:

<#@ template language="C#" #>
<#@ parameter type="System.Collections.Generic.List<System.String>" name="Names" #>

<# foreach (string name in Names) { #>
Line <#= name #>
<# } #>

关于c# - 将列表值传递给 t4 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27971069/

相关文章:

c# - 带有多个项目的 TypeLITE

typescript - 是否有用于 TypeScript 的代码生成 API?

.net - 如何在VS2010中指定T4(文本模板)以使用C#4.0?

c# - 从 T4 类访问主机对象

c# - 网络核心 : Create Generic Repository Interface Id Mapping for All Tables Auto Code Generation

c# - 基于方法参数值的注入(inject)上下文绑定(bind)

c# - IE8/IE9 工具栏 Cookie 检查

c# - C#异步接收会导致系统范围内的网络崩溃!

c# - EF Code First 方法中 DbContext 类的空构造函数的目的是什么?

visual-studio-2010 - 如何使用T4在相对路径上打开文件?