T4模板之文本模板
網址:https://docs.microsoft.com/en-us/visualstudio/modeling/design-time-code-generation-by-using-t4-text-templates?view=vs-2017
T4模板在平時我們其實都會或多或少的遇到。最多的用在實體與數據庫的映射上面。
這裏只記錄一下他的語法。
需要的插件:vs2017
T4代碼高亮插件:Devart T4 Editor
T4生成多文件:T4 Toolbox (使用這個可以很好的生成我們的實體映射,這篇不會使用到)
①我們需要創建一個文本模板,運行時文本模板我們不用管
查看這個*.tt文件屬性
文本模板由以下部分組成:
-
指令 - 控制模板處理方式的元素。
-
文本塊 - 直接復制到輸出的內容。
-
控制塊 - 將變量值插入文本的程序代碼,並控制文本的條件或重復部分。
①T4指令
1.模板指令
<#@ template [language="C#"] [compilerOptions="options"] [culture="code"] [debug="true"] [hostspecific="true"] [inherits="templateBaseClass"] [visibility="internal"] [linePragmas="false"] #>
2.參數指令
<#@ parameter type="Full.TypeName" name="ParameterName" #>
3.輸出指令
<#@ output extension=".fileNameExtension" [encoding="encoding"] #>
4.Assembly指令==代碼中引用程序集
<#@ assembly name="[assembly strong name|assembly file name]" #>
5.導入指令==代碼中的using 命名空間
<#@ import namespace="namespace" #>
6.包含指令(可以把相同的文件單獨寫個然後進行包含指令)
<#@ include file="filePath" [once="true"] #>
②文本塊
③控制塊
-
<# Standard control blocks #>
可以包含語句。 -
<#= Expression control blocks #>
可以包含表達式。 -
<#+ Class feature control blocks #>
可以包含方法,字段和屬性。
④轉義字符
\<# ... \#>
下面是簡單的了解下
①輸出.txt文本
<#@ template debug="false" hostspecific="false" language="C#" #> <#@ output extension=".txt" #> Hello Word
②使用循環輸出多行文本
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".txt" #>
<# // 註意你的空格,(註釋) #>
<#for(int i=0;i<4;i++){#>
Hello Word
<#}#>
③自定義方法進行調用
<#@ template debug="false" hostspecific="false" language="C#" #> <#@ output extension=".txt" #> <# // 註意你的空格 #> <#for(int i=0;i<4;i++){#> Hello Word i前:<#=i #> ,i後:<#= TestFu(i) #> <#}#> <#+ //可以寫我們的自定義的方法 private int TestFu(int n) { return n+1; } #>
④輸出.cs文件
<#@ template debug="false" hostspecific="false" language="C#" #> <#@ output extension=".cs" #> namespace T4Demo { public class T4Test { /// <summary> /// ID /// </summary> public int ID { get; set;} /// <summary> /// 姓名 /// </summary> public string Name { get; set;} } }
⑤添加引用
<#@ template debug="false" hostspecific="false" language="C#" #> <#@ output extension=".cs" #> namespace T4Demo { using System; public class T4Test { /// <summary> /// ID /// </summary> public int ID { get; set;} /// <summary> /// 姓名 /// </summary> public string Name { get; set;} /// <summary> /// 出生日期 /// </summary> public DateTime? Birth { get; set;} } }
⑥轉義字符
T4模板之文本模板