1

我开始研究 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 方法存在于类块中,但它们本身可以使用示例代码写入,即转义代码块。

我怎样才能做到这一点?

4

2 回答 2

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
'...
于 2008-10-15T11:20:19.123 回答
1

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

<#@ template language="C#" #>
<# HelloWorld(); #>
<#+
    private string _field = "classy";
    private void HelloWorld()
    {
        for(int i = 1; i <= 3; i++)
        {
#>
Hello <#=_field#> World <#= i #>!
<#+
        }
    }
#>
于 2008-10-15T11:18:43.523 回答