T4,即4個T開頭的英文字母組合:Text Template Transformation Toolkit。T4(Text Template Transformation Toolkit)是微軟官方在VisualStudio 2008中開始使用的代碼生成引擎。簡單的說就是可以根據模板生成你想要的文件,可以使類文件,文本文件,HTML等等。
VS本身只提供一套基於T4引擎的代碼生成的執行環境,由下面程序集構成:
Microsoft.VisualStudio.TextTemplating.10.0.dll
Microsoft.VisualStudio.TextTemplating.Interfaces.10.0.dll
Microsoft.VisualStudio.TextTemplating.Modeling.10.0.dll
Microsoft.VisualStudio.TextTemplating.VSHost.10.0.dll
T4模板編輯器插件:
vs默認編輯器無高亮,無提示。T4編輯器有多款,這只是其中一個。
T4的編輯工具下載地址http://t4-editor.tangible-engineering.com/Download_T4Editor_Plus_ModelingTools.html
T4基本語法:
T4語法主要包括三類:
- 指令塊 - 向文本模板化引擎提供關於如何生成轉換代碼和輸出文件的一般指令。
#@ output extension=".txt" #>
- 文本塊 - 直接復制到輸出的內容。
<#@ output extension=".txt" #> Hello
- 控制塊 - 向文本插入可變值並控制文本的條件或重復部件的程序代碼,不能在控制塊中嵌套控制塊。
- 標准控制塊。
<# for(int i = 0; i < 4; i++) { #> Hello! <# } #>
- 表達式控制塊。
<#= 2 + 3 #>
- 類功能控制塊。
-
<#@ output extension=".txt" #> Squares: <# for(int i = 0; i < 4; i++) { #> The square of <#= i #> is <#= Square(i+1) #>. <# } #> That is the end of the list. <#+ // Start of class feature block 類功能控制塊以
<#+ ... #>
符號分隔。 private int Square(int i) { return i*i; } #> -
List of Squares: <# for(int i = 0; i < 4; i++) { WriteSquareLine(i); } #> End of list. <#+ // Class feature block 類功能塊包含文本塊 private void WriteSquareLine(int i) { #> The square of <#= i #> is <#= i*i #>. <#+ } #>
- 標准控制塊。
指令:
<#@ DirectiveName [AttributeName = "AttributeValue"] ... #>
- T4 模板指令。
<#@ template [language="VB"] [compilerOptions="options"] [culture="code"] [debug="true"] [hostspecific="true"] [inherits="templateBaseClass"] [visibility="internal"] [linePragmas="false"] #>
- T4 參數指令。
<#@ parameter type="Full.TypeName" name="ParameterName" #>
- T4 輸出指令。
<#@ output extension=".fileNameExtension" [encoding="encoding"] #>
- T4 程序集指令。
<#@ assembly name="[assembly strong name|assembly file name]" #>
- T4 導入指令。
<#@ import namespace="namespace" #>
- T4 包含指令。
<#@ include file="filePath" #>
- T4 CleanUpBehavior 指令。
<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #>