T4 模板不使用列表作为参数

T4 Template not working with List as a parameter

我有一个 T4 模板。

<#@ template language="C#" #>
<#@ import namespace="System.Collections.Generic"#>
<#@parameter name="Stats" type="System.Collections.Generic.List<SiteStat>" #>
<#@parameter name="Cnt" type="System.Int32" #>

    This is a test.  Why is this not working <#= Cnt #>
    <table>
        <# foreach (SiteStat stat in Stats)
           { #>
             <tr><td>Test name <#= stat.node #> </td>
                 <td>Test value <#= stat.region #> </td> </tr>
        <# } #>
     </table>

简单整数正在正常传递到系统中 但更复杂的列表不是。

它不会在 table 标签内生成任何内容。

编辑 2021 年 4 月 26 日: 我的 SiteStat 定义如下

namespace ScheduledJobsService
{
    [Serializable]
    public struct SiteStat
    {
        public string region { get; set; }
        public string district { get; set; }
        public string system { get; set; }
        public string node { get; set; }
        public float a1score { get; set; }
        public float a1delta { get; set; }
        public float a7score { get; set; }
        public float a7delta { get; set; }
        public SiteStat(string region, string district, string system, string node, float a1score, float a1delta, float a7score, float a7delta)
        {
            this.region = region;
            this.district = district;
            this.system = system;
            this.node = node;
            this.a1score = a1score;
            this.a1delta = a1delta;
            this.a7score = a7score;
            this.a7delta = a7delta;
        }
    }
}

我试过在我的 teplate 中使用 ScheduledJobsService.SiteStat

<#@parameter name="Stats" type="System.Collections.Generic.List<ScheduledJobsService.SiteStat>" #>

但它不会编译,声称 SiteStat 不存在于 ScheduledJobsService 命名空间中

尝试将 完整类型 名称传递给 SiteStat

此外,请记住,根据文档 here

You can declare parameters of any remotable type. That is, the type must be declared with SerializableAttribute, or it must derive from MarshalByRefObject. This allows parameter values to be passed into the AppDomain in which the template is processed.

在 .tt 文件的末尾,将您的参数添加为“Class 功能控制块”中的 public class 成员。 此块必须转到文件末尾。

<#+
public SiteStat Stats{ get; set; }
#>

您可以按如下方式使用您的模板:

YourTemplate t = new YourTemplate
{
    Stats = yourStatsObj
};

有关 T4 语法的详细信息,请参阅 MSDN 文章编写 T4 文本模板。 Writing a T4 Text Template