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

博客介绍了C#代码生成相关内容,将生成的文件保存为Account.cs和Check.cs。若要改变Account Balance类型为浮点型,只需修改ConstructorParameterType属性为float,重新生成Account.cs,无需手工修改该文件,也不用修改Check.cs代码。
 CodeSmith生成可变化的代码,其实是先利用CodeSmith生成一个基类,然后自定义其它类继承于该类。当我们重新生成基类时CodeSmith不要接触继承的子类中的代码。看下面的这段模版脚本:<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

None.gif<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Base class generator." %>
None.gif
<%@ Property Name="ClassName" Type="System.String" Description="Name of the class." %>
None.gif
<%@ Property Name="ConstructorParameterName" Type="System.String" Description="Constructor parameter name." %>
None.gif
<%@ Property Name="ConstructorParameterType" Type="System.String" Description="Data type of the constructor parameter." %>
None.gif
class <%= ClassName %>
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
<%= ConstructorParameterType %> m_<%= ConstructorParameterName %>;
InBlock.gif 
InBlock.gif    
public <%= ClassName %>(<%= ConstructorParameterType %> <%= ConstructorParameterName %>)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        m_
<%= ConstructorParameterName %> = <%= ConstructorParameterName %>
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

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

<?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" />PIC058.JPG

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

 1None.gifclass Account
 2ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 3InBlock.gif    int m_balance;
 4InBlock.gif 
 5InBlock.gif    public Account(int balance)
 6ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 7InBlock.gif        m_balance = balance
 8ExpandedSubBlockEnd.gif    }

 9InBlock.gif
10ExpandedBlockEnd.gif}

11None.gif
12None.gif

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

1None.gifclass Checking : Account
2ExpandedBlockStart.gifContractedBlock.gifdot.gif{
3InBlock.gif    public Checking : base(0)
4ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
5ExpandedSubBlockEnd.gif    }

6ExpandedBlockEnd.gif}

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

转载于:https://www.cnblogs.com/Terrylee/archive/2005/12/28/306222.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值