CodeSmith教程(2) 编写第一个代码模板2013-01-19 csdn mapdigit在CodeSmith 使用教程(1): 概述我们通过使用CodeSmith从数据库自动生成NHiberate代码,可以了解到使用CodeSmith自动 生成代码的基本步骤:选择使用合适的模板,CodeSmith随开发包自带了大量常用的模板,如果找不到合适的模板,CodeSmith支持自定义模板。为模板选择合适的参数设置。自动生成代码(可以为任意类型的代码,C#,Java, .XML 文本等)

其核心为代码模板文件,随CodeSmith自带了不少常用的模板,可以通过模板浏览器来查询,此外网上也有很多第三方开发的 模板,在使用前可以先查查是否已有现成的模板,或是可以通过修改现有的模板来完成自动生成代码的需要。在开发应 用时,很多人都喜欢通过复制以前的项目中的代码,然后通过修改以满足新项目,这些重用的代码通常具有很多共性(可以想想 C++的模板类,C#的Generic等),CodeSmith就是用来为这些具有相似性的代码创建模板,然后通过设置属性(代码直接的不同 点),就可以自动创建所需代码。本例通过一个简单的例子来介绍创建一个自定义代码模板的方法。CodeSmith提供了 Visual Studio的集成开发环境的支持,本例也是通过创建模板自动生成简化每个的C#项目都需要的  AssemblyInfo.cs, 在开发C# 应用时,一般是通过手工修改AssemblyInfo.cs的中属性(或者是Copy & Paste :-)).首先我们使用 Visual Studio创建一个C# HelloWorld下面(Console或是WinForm项目都可以),可以打开项目中的 AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices;using System.Runtime.InteropServices;// General Information about an assembly is controlled through the following// set of attributes. Change these attribute values to modify the information// associated with an assembly.[assembly: AssemblyTitle("HelloWorld")][assembly: AssemblyDescription("")][assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("HelloWorld")] [assembly: AssemblyCopyright("Copyright ? Microsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components.If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("72797715-64b9-4bab-a49f-f55e8a0a18d7")] // Version information for an assembly consists of the following four values: // //Major Version //Minor Version //Build Number //Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the "*" as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
为了使用CodeSmith,我们在HelloWorld中添加CodeSmith的项目文件 并创建一个模板文件AssemblyInfo.cst
