zoukankan      html  css  js  c++  java
  • 在Visual Studio中使用T4 Templates 生成代码

    在没有看过Hilton Giesenow(How Do I: Create and Use T4 Templates.)的视频之前,我还没意识到在Visual Studio 2008 中使用T4是何等的简单。

    如果您对在Visual Studio中使用T4 Templates感兴趣的话,请确认您已经下载并安装T4 Editor(能够在创建代码生成模板的时候给以部分智能提示)

    快速创建一个T4 Template 例子:
    在Visual Studio 2008中创建一个Console Application,选择“添加新项”选择“文本文件”。在给文件命名的时候,请确保您使用“tt”扩展名。正如您在下文中看到的,我添加了一个名为MyTemplate.tt的文本文件。Visual Studio将会自动为您创建MyTemplate.cs文件。
     

    Write some T4 Template Tags, which is basically inline ASP, in the MyTemplate.tt file as such:
    在MyTemplate.tt中编写如下标记(类似与asp) 

    <#@ template language="C#" #>
    using System;

    public class TestClass
    {
        public void WriteToConsole()
        {
    <#        for (int i = 0; i < 10; i++) { #>
            Console.WriteLine(<#= i.ToString() #>);
    <#        } #>
        }
    }
     

    当您保存此文件时,以下C#代码将被自动生成到MyTemplate.cs文件中:
     

    using System;

    public class TestClass
    {
        public void WriteToConsole()
        {
            Console.WriteLine(0);
            Console.WriteLine(1);
            Console.WriteLine(2);
            Console.WriteLine(3);
            Console.WriteLine(4);
            Console.WriteLine(5);
            Console.WriteLine(6);
            Console.WriteLine(7);
            Console.WriteLine(8);
            Console.WriteLine(9);
        }
    }
     
    在Program.cs文件中编写代码运行您生成的代码
     

    using System;

    namespace ConsoleApplication5
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                new TestClass().WriteToConsole();
                Console.ReadLine();
            }
        }
    }
     
    此时您可以运行他,在 Visual Studio 2008 中使用T4 Template 生成的代码。

    找不出一个强有力的理由在生成器以及O/R Mapper的情况下使用T4 Template来生成代码。然而,至少他给我们提供一种选择。
    希望对您有所帮助
    Denny.Dong
  • 相关阅读:
    关于SVN出现 svn working copy locked的原因及解决方法
    安装SVN客户端重启电脑之后,右键未出现SVN选项的原因
    Django—工程创建以及models数据库易错点
    tornado之文件上传的几种形式form,伪ajax(iframe)
    python 收录集中实现线程池的方法
    python 多线程,进程的理解
    python之路 序列化 pickle,json
    collections模块方法详解
    python之路 socket,socketsever初探
    SQL- 约束
  • 原文地址:https://www.cnblogs.com/netwenchao/p/1716810.html
Copyright © 2011-2022 走看看