CodeSmith實用技巧(五):利用繼承產生可變化的代碼

來源:互聯網
上載者:User
 用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檔案的任何代碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.