T4模版基础例子

时间:2023-03-10 00:37:34
T4模版基础例子
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ output extension=".txt" #> <#
IServiceProvider serviceProvider = (IServiceProvider)this.Host;
EnvDTE.DTE dte = (EnvDTE.DTE) serviceProvider.GetService(typeof(EnvDTE.DTE));
#> <#
string path = Path.Combine(dte.ActiveDocument.Path,"aa.txt");
string line = string.Empty;
using(StreamReader reader = new StreamReader(path))
{
line = line = reader.ReadToEnd();
}
#> <#=line#>

上面代码的作用是通过T4模版来读取与模版文件同一目录中的aa.txt的内容,并生成文件到指定的文件中。

基础语法解释:

hostspecific="true" ,如果将此特性的值设置为 true,则会将名为 Host 的属性添加到由文本模板生成的类中。

EnvDTE相关信息参考,https://msdn.microsoft.com/zh-cn/library/envdte.aspx

EnvDTE 是包含 Visual Studio 内核自动化的对象和成员的用程序集包装的 COM 库。