代码生成器 CodeSmith 的使用(一)

来源:互联网 发布:疯狂的美工助手要钱吗 编辑:程序博客网 时间:2024/04/27 14:41


由于在项目中经常要会用到数据库的 CRUD 操作(增、删、改、查),而且还使用的是orm 框架将数据库表名和表中的的字段映射成相应的类属性。如果把大量的时间用到手工输入数据库表中的字段,除了能练习打字速度外,对软件工程师来说,对编程能力的提高似乎没有什么意义,为了提高开发效率,节省时间,我工作之余花了大量的时间来学习研究CodeSmith 在生成数据库表中字段的模板的设计,在此记下自己的 CodeSmith 学习笔记。

  这是新建的一个 CsharpTemplate.cst 模板文件的内容

<%-- Name:Author: Description: --%><%@ Template Language="C#" TargetLanguage="Text" %><%@ Property Name="SampleStringProperty" Default="SomeValue" Type="System.String" %><%@ Property Name="SampleBooleanProperty" Default="True" Type="System.Boolean" %>My static content here.My dynamic content here: "<%= SampleStringProperty %>"Call a script method: <%= SampleMethod() %><% if (SampleBooleanProperty) { %>My conditional content here.<% } %><script runat="template">// My methods here.public string SampleMethod(){  return "Method output.";}</script>

  开头的是注释, 表示文件的作者,名称和功能描述

  接下来   <%@ Template Language="C#" TargetLanguage="Text" %> 就是模板的说明内容

 <%@ Property Name="SampleStringProperty" Default="SomeValue" Type="System.String" %>
 这是属性类型的设置 它会生成一个 System.String 类型的字段  默认的值被设置成 SomeValue  Name是属性模板的名称,这个可以自命名, 模板的东西通常会放在 <% %> 里面,是成对出现的。比如要输出 System.String 类型的值,就要这么写
 My dynamic content here: "<%= SampleStringProperty %>", 注意在<%> 前有个=号, 前面的 ”My dynamic content here“ 完全可以根据实际的需要来修改

 在 模板中写代码片段时,也是放在 <%> 中的, 像例子中的这个 <% if (SampleBooleanProperty) { %>
My conditional content here.
<% } %> 是一个 if语句判断, 如果是 true ,就会输出 My conditional content here.,注意: 花括号{ 也要放在 <%>内 花括号与花括号不能直接相邻,如果是 一个函数, 则要放在 <script runat="template"> </script>中, 此时的花括号可以相邻,书写方式同在C#中的 书写方式一致。

这段代码会生成这样一个输出:

My static content here.My dynamic content here: "SomeValue"Call a script method: Method output.My conditional content here.


 

 

0 0
原创粉丝点击