【问题标题】:T4 Template not working with List as a parameterT4 模板不使用列表作为参数
【发布时间】:2021-07-18 02:06:20
【问题描述】:

我有一个 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>

简单的整数很好地传入系统 但更复杂的 List 不是。

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

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 命名空间中不存在

【问题讨论】:

  • List&lt;SiteStat&gt;? SiteStat 类型不是此模板中包含的类型。此外,我会使用 XML 或 JSON 传递数据并在模板内序列化,因为传递类型参数的类型既烦人又棘手

标签: c# t4


【解决方案1】:

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

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

您可以声明任何远程类型的参数。也就是说,类型 必须用SerializableAttribute 声明,或者它必须派生自 MarshalByRefObject。这允许将参数值传递到 处理模板的 AppDomain。

【讨论】:

    【解决方案2】:

    在 .tt 文件的末尾,将您的参数添加为“类功能控制块”内的公共类成员。 这个块必须到文件的末尾。

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

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

    YourTemplate t = new YourTemplate
    {
        Stats = yourStatsObj
    };
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      相关资源
      最近更新 更多