• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
鱼要的是海洋,鸟要的是天空,我要的是自由!
平凡的人不平凡的人生
博客园    首页    新随笔    联系   管理    订阅  订阅

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文件的任何代码。

posted @ 2007-06-15 11:06  伊凡  阅读(298)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3