用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檔案的任何代碼。