好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

用 CodeSmith 生成可变化的代码,其实是先利用 CodeSmith 生成一个基类,然后自定义其它类继承于该类。当我们重新生成基类时 CodeSmith 不要接触继承的子类中的代码。看下面的这段模版脚本: % @CodeTemplateLanguage = " C# " TargetLanguage = " C# " Desc

用 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 %>
}
}

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

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

1 class 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 文件代码:

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

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

查看更多关于CodeSmith实用技巧(五):利用继承生成可变化的代码的详细内容...

  阅读:36次

上一篇: apache瘦身大行动---够用就好

下一篇:OAFFlexField中数据库与页面的前后台数据类型转换