在沒有看過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