如何在T4 ClassBlock方法中使用模板?

时间:2008-10-15 10:53:03

标签: t4

我开始研究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方法,但是它们本身可以使用代码来编写,即转义代码块。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

你可以写.....

<#@ 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
'...

答案 1 :(得分:1)

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

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