【问题标题】:How do I use templates inside a T4 ClassBlock method?如何在 T4 ClassBlock 方法中使用模板?
【发布时间】:2008-10-15 10:53:03
【问题描述】:

我开始研究 T4 的代码生成。

我知道您有一个基本模板,您可以在其中嵌入小块 c#/vb,它可以执行巧妙的操作...

<#@ template language="VB" debug="True" hostspecific="True" #>
<#@ output extension=".vb" debug="True" hostspecific="True" #>
Imports System
<#For Each Table as String in New String(0 {"Table1","Table2"}#>
Public Class <#=Table#>DA
    Public Sub New
        <#= WriteConstructorBody() #>
    End Sub 
End Class
<#Next#>
<#+
    Public Function WriteConstructorBody() as String
        return "' Some comment"
    End function
#>

这很棒..但是我希望能够编写我的主要块......

<#@ template language="VB" debug="True" hostspecific="True" #>
<#@ output extension=".vb" debug="True" hostspecific="True" #>
Imports System
<# 
For Each BaseTableName as String in New String(){"Table1","Table2"} 
    WriteRecDataInterface(BaseTableName) 
    WriteRecDataClass(BaseTableName) 
    WriteDAInterface(BaseTableName) 
    WriteDAClass(BaseTableName) 
Next 
#>

然后我希望能够让 WriteX 方法存在于类块中,但它们本身可以通过示例代码写入,即转义代码块。

我怎样才能做到这一点?

【问题讨论】:

    标签: t4


    【解决方案1】:

    你可以写.....

    <#@ template language="VB" debug="True" hostspecific="True" #>
    <#@ output extension=".vb" debug="True" hostspecific="True" #>
    Imports System
    <# 
    For Each BaseTableName as String in New String(){"Table1","Table2"} 
        WriteRecDataInterface(BaseTableName) 
    
        ' WriteRecDataClass(BaseTableName) 
        ' WriteDAInterface(BaseTableName) 
        ' WriteDAClass(BaseTableName) 
    Next 
    #>
    
    
    <#+ Public Sub WriteRecDataInterface(BaseTableName as String)#>
        Some Templated unescaped code might go here
        <#+ For SomeLoopVar as Integer = 1 to 10 #>
            Some Templated unescaped code might go here
        <#+ Next #>
        Some Templated unescaped code might go here
    <#+ End Sub #>
    '...
    '...
    ' Other Subs left out for brevity
    '...
    

    【讨论】:

      【解决方案2】:

      您似乎可以在类块中将静态输出与模板代码混合使用。下面是一个 C# 示例:

      <#@ template language="C#" #>
      <# HelloWorld(); #>
      <#+
          private string _field = "classy";
          private void HelloWorld()
          {
              for(int i = 1; i <= 3; i++)
              {
      #>
      Hello <#=_field#> World <#= i #>!
      <#+
              }
          }
      #>
      

      【讨论】:

      • 我不得不费力寻找您示例中的静态文本......对我来说,
      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      相关资源
      最近更新 更多