在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