CodeSmith实用技巧(五):利用继承生成可变化的代码

 CodeSmith生成可变化的代码,其实是先利用CodeSmith生成一个基类,然后自定义其它类继承于该类。当我们重新生成基类时CodeSmith不要接触继承的子类中的代码。看下面的这段模版脚本:
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Base class generator." %>
<%@ Property Name="ClassName" Type="System.String" Description="Name of the class." %>
<%@ Property Name="ConstructorParameterName" Type="System.String" Description="Constructor parameter name." %>
<%@ Property Name="ConstructorParameterType" Type="System.String" Description="Data type of the constructor parameter." %>
class <%= ClassName %>
{
    
<%= ConstructorParameterType %> m_<%= ConstructorParameterName %>;
 
    
public <%= ClassName %>(<%= ConstructorParameterType %> <%= ConstructorParameterName %>)
    
{
        m_
<%= ConstructorParameterName %> = <%= ConstructorParameterName %>
    }

}

执行该模版并输入如下数据:

该模版生成的代码可能如下:

 1class Account
 2{
 3    int m_balance;
 4 
 5    public Account(int balance)
 6    {
 7        m_balance = balance
 8    }

 9
10}

11
12

把生成的文件保存为Account.cs文件。这时我们可以编写第二个类生成Check.cs文件代码:

1class Checking : Account
2{
3    public Checking : base(0)
4    {
5    }

6}

现在如果需要改变Account Balance的类型为浮点型,我们只需要改变ConstructorParameterType属性为float,并重新生成Account.cs文件即可而不需要直接在Account.cs中进行手工修改,并且不需要修改Check.cs文件的任何代码。

作者:TerryLee
出处:http://terrylee.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
posted @ 2005-12-28 08:33 TerryLee 阅读(1494) 评论(0)  编辑 收藏 所属分类: CodeSmith

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  博客园首页

  新闻频道

  社区

  小组

  博问

  网摘

  闪存

  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
成果网帮您增加网站收入


相关链接: