码迷,mamicode.com
首页 > 其他好文 > 详细

T4语法快速入门

时间:2017-04-21 16:50:08      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:分享   blog   官方   ado   date   html   简单   技术   tsp   

1.什么是T4?

 T4,即4个T开头的英文字母组合:Text Template Transformation Toolkit。T4(Text Template Transformation Toolkit)是微软官方在VisualStudio 2008中开始使用的代码生成引擎。简单的说就是可以根据模板生成你想要的文件,可以使类文件,文本文件,HTML等等。

2.vs插件的安装

T4的编辑工具下载地址http://t4-editor.tangible-engineering.com/Download_T4Editor_Plus_ModelingTools.html
VS默认的编辑工具无高亮,无提示,错误不易定位。 没这个工具,真心不想写任何T4代码。

技术分享

 3.T4语法

<# 标准控制块 #> 可以包含语句。

<#= 表达式控制块 #> 可以包含表达式。

<#+ 类特征控制块 #> 可以包含方法、字段和属性,就像一个类的内部

<#@ 指令 属性=“值”#>

 

 

3.1.标准控制块

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ import namespace="System" #>
<#@ output extension=".txt" #>

<#
    int a=10;
    string b = "20"; 
    DateTime c = DateTime.Now;
    for(int i = 0; i < 4; i++)
    {
#>
测试
<#
    } 
    
#>

 

3.2.表达式控制块

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ import namespace="System" #>
<#@ output extension=".txt" #>

<#
    int a=10;
    string b = "20"; 
    DateTime c = DateTime.Now;
    for(int i = 0; i < 4; i++)
    {
#>
测试<#=i#> <#=string.Format("{0},{1},{2}",a,b,c)#>
<#
    } 
    
#>

 

3.3.类特征控制块

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".txt" #>



<#
    int a=10;
    string b = "20"; 
    DateTime c = DateTime.Now;
    for(int i = 0; i < 4; i++)
    {
#>
测试<#=i#> 
<#=string.Format("{0},{1},{2}",a,b,c)#>
<#=1+1#>
<#=config.TableName#>
<#
    } 
    
#>
<#+
    public class config
    {
        public static readonly string ConnectionString = "Data Source=(local);Initial Catalog=NFineBase;User ID=sa;Password=hjf19870810;";
        public static readonly string DbDatabase = "NFineBase";
        public static readonly string TableName = "Sys_Test";
    }
#>

 

3.4.指令

<#@ output extension=".cs" #>
告诉T4引擎生成文件的后缀名是.cs;

<#@ template debug="false" hostspecific="false" language="C#" #>
langeuage:输出语言,有效值C#、VB,默认为C#
debug:是否启用调试,有效值true、false,默认为false。
hostspecific:有效值true、false,默认为false。如果将此特性的值设置为 true,则会将名为 Host 的属性添加到由文本模板生成的类中。 该属性是对转换引擎的宿主的引用,并声明为Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost。
inherits:可以指定模板的程序代码可以继承自另一个类,这个类也可以从文本模板生成。目前木有使用过,基本上可以忽略

<#@ assembly name="System"#>
告诉T4引擎编译运行时引用System程序集

<#@ import namespace="System.Data"#>
告诉T4引擎编译运行时引用某个名称空间。

 

T4语法快速入门

标签:分享   blog   官方   ado   date   html   简单   技术   tsp   

原文地址:http://www.cnblogs.com/lgxlsm/p/6744061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!