将列表值传递给t4模板

Kai*_*Kai 3 c# t4

我在这里使用代码将参数传递给模板文件.

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();
Run Code Online (Sandbox Code Playgroud)

但每次,我得到的都是Topic列表中的最后一个值("5").

<#@ 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
Run Code Online (Sandbox Code Playgroud)

我怎样才能使我能够在模板的主题列表中生成每个值?像预期的输出.

对不起这个问题的糟糕英语和格式.

gmi*_*ley 6

我没有使用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] #>
<# } #>
Run Code Online (Sandbox Code Playgroud)

您也可以删除TimesToRepeat并执行foreach:

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

<# foreach (string name in Names) { #>
Line <#= name #>
<# } #>
Run Code Online (Sandbox Code Playgroud)